Code example:
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("src/main/resources/SomeText.txt", true);
writer.append("");
writer.append("");
writer.write("File");
writer.write("Writer");
writer.append("");
writer.write("Test");
writer.close();
}
Textfile example:
| Textfile | Textfile I want | Textfile I get |
|:--------:|:---------------:|:--------------:|
|One |One |One
|Two |Two |Two
|Three |File |Three
|Four |Writer |Four
|Five |Five |FiveFileWriterTest
|Test |
I read that you should use new FileWriter("text.txt", true)
but that doesn't work.
I want to skip some lines that I don't need to write.
CodePudding user response:
First clarify the different I/O classes for a file:
- your given
FileWriter
writes to a file, i.e. equivalent to appends - in contrast - a
FileReader
reads from an existing file
As far as I know there is no such thing as a FileUpdater in standard Java packages which can read lines from a file an skip some while overwriting others.
But the concept of update, replace or skip lines can be implemented by combining both classes Reader and Writer.
See also GeeksforGeeks: File handling in Java using FileWriter and FileReader
Write to a text-file from an array of lines
Similar to what given code already didL
FileWriter writer = new FileWriter("src/main/resources/SomeText.txt", true);
List<String> lines = List.of("1", "2", "3", "4", "5");
for (line in lines) {
writer.append(line); // equivalent with writer.write(line)
writer.append("\n"); // add a newline
}
writer.close(); // this will flush and write from buffer to file
Now you should have 5 new lines in the file.
Read your given text-file into an array of lines
Suppose you want to read from a given text-file src/main/resources/SomeText.txt
.
You can use FileReader
to read char by char or a special class which buffers the chars and allows to read entire lines: BufferedReader
and its method readLine()
:
BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/SomeText.txt"));
List<String> lines = new ArrayList<String>(); // empty array list
while (reader.ready()) { // while not End of File (EOF)
lines.add(reader.readLine()); // read next line and add to the list
}
reader.close(); // this will close the file
// count the lines and print to console
System.out.println(lines.size());
Count of read lines should be 5 if the file was created freshly before. Otherwise if the file existed with lines before, the line-count should be 5 more than before appending/writing the new ones.
Insert lines
Now you can combine both recipes to read a given file and add/insert new lines where needed.
CodePudding user response:
Just change writer.append(""); to writer.write("");
A line that is skipped, is the same as a line that has nothing written