Reputation: 47
When i run the code everything works fine but the contents are not written to target.txt.
public class SrtExtractor {
public static void main(String[] args) throws IOException {
Path source = Paths.get("files/loremipsum.txt");
Path target = Paths.get("files/target.txt");
Charset charSet = Charset.forName("US-ASCII");
BufferedReader reader = Files.newBufferedReader(source, charSet);
BufferedWriter writer = Files.newBufferedWriter(target, charSet);
String temp;
ArrayList<String> list = new ArrayList<>();
while((temp = reader.readLine())!=null){
list.add(temp);
System.out.println(temp);
}
for(int i = 0; i<list.size(); i++)
{
writer.append(list.get(i));//why this line is not working???
}
}
}
Upvotes: 1
Views: 95
Reputation: 2129
You're using the BufferedWriter
class - In this case, the contents of your write are still in the Buffer. writer.flush();
needs to be called to flush out the contents of the Buffer and write them to the underlying stream.
flush()
is also called automatically when close()
is called. close()
should be called when your program is done with it's resources, in order to avoid memory leaks. Proper closing of resources can be difficult to do correctly, but Java 7 added a new try-with-resources construct to help programmers properly close their resources.
Here's your example rewritten to use the try-with-resources construct. This will ensure that both of your streams get properly closed, even if an exception occurs while processing the file. It's essentially the same as calling close()
on your reader and writer, but it's safer and uses less code.
public class SRTExtractor {
public static void main(String[] args) throws IOException {
Path source = Paths.get("files/loremipsum.txt");
Path target = Paths.get("files/target.txt");
Charset charSet = Charset.forName("US-ASCII");
try (
BufferedReader reader = Files.newBufferedReader(source, charSet);
BufferedWriter writer = Files.newBufferedWriter(target, charSet);
) {
String temp;
ArrayList<String> list = new ArrayList<>();
while ((temp = reader.readLine()) != null) {
list.add(temp);
System.out.println(temp);
}
for (int i = 0; i < list.size(); i++) {
writer.append(list.get(i));
}
}
}
}
Upvotes: 3
Reputation: 1427
As everyone says, you should add writer.close()
.
By other side, I think that the best way to write on a text file is this (it always runs for me):
File file = new File(path);
FileOutputStream fout = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fout);
Writer w = new BufferedWriter(osw);
for(...){
w.write(...);
}
Upvotes: 0
Reputation: 3442
for(int i = 0; i<list.size(); i++) {
writer.append(list.get(i));
}
writer.close(); //Add this
reader.close(); //Add this
You haven't indicated that you were done writing to the file. Until you say close()
the file isn't actually being written, the text is just sitting in the BufferedWriter
.
Upvotes: 1