forked from aidanrahill/topics-string
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWriteString.java
More file actions
56 lines (47 loc) · 1.78 KB
/
ReadWriteString.java
File metadata and controls
56 lines (47 loc) · 1.78 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
import java.io.*;
class ReadWriteString {
public String ReadFile(String fileName) {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
public void WriteString(String string, String fileName) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(string);
} catch (IOException e) {
e.printStackTrace();
}
}
public int countChar(String fileName) throws IOException {
int count = 0;
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
while (br.ready()) {
br.read();
count++;
}
return count;
}
public static void main(String[] args) throws IOException {
ReadWriteString fileHandler = new ReadWriteString();
// Reading from a file
String fileNameToRead = "input.txt";
String contentRead = fileHandler.ReadFile(fileNameToRead);
System.out.println("Content read from file:\n" + contentRead);
// Writing to a file
String contentToWrite = "Hello, this is content to be written!";
String fileNameToWrite = "output.txt";
fileHandler.WriteString(contentToWrite, fileNameToWrite);
System.out.println("Content written to file.");
// Counting from a file
String fileName = "output.txt";
System.out.println(fileHandler.countChar("output.txt"));
}
}