-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileIO.java
More file actions
65 lines (61 loc) · 2.13 KB
/
FileIO.java
File metadata and controls
65 lines (61 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.mycompany.project2;
/**
*
* @author alihabibi
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class FileIO {
//The writeToFile method takes a filename and data to be written as input and writes
//the data to the file with the specified filename.
public static void writeToFile(String filename, String data) {
//PrintWriter pw = new PrintWriter (new BufferedOutPutStream((new FileOutputStream("filename")));
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileOutputStream(filename,true));
writer.write(data);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
if (writer != null) {
writer.close();
}
writer.close();
}
}
/*The readFromFile method takes a filename
as input and reads the contents of the file with the specified filename and returns it as a string.*/
public static String readFromFile(String filename) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
File file = new File(filename);
reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append(System.lineSeparator());
line = reader.readLine();
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return stringBuilder.toString();
}
}