So I have a background in c++ and I am trying to learn java. Everything is pretty similar. I am having a problem thought with file i/o. So I am messing around and doing really simple programs to get the basic ideas. Here is my code to write data to a file. My code makes a file, but when I open the file it is empty and does not contain the string I told it to write.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.io.PrintWriter;
public class PracticeWithArraysAndIO
{
public static void main(String[] args) throws IOException
{
//Declaring a printWriter object
PrintWriter out = new PrintWriter("myFile.txt");
out.println("hello");
}
}
The output is buffered and needs to be flush()
ed to be written to a file.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.io.PrintWriter;
public class PracticeWithArraysAndIO {
public static void main(String[] args) {
PrintWriter out = new PrintWriter("myFile.txt");
out.println("hello");
out.flush();
}
}
But you don't need to flush explicitly because that will happen anyway when you close()
the writer, which you ought to be doing.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.io.PrintWriter;
public class PracticeWithArraysAndIO {
public static void main(String[] args) {
PrintWriter out = new PrintWriter("myFile.txt");
try {
out.println("hello");
} finally {
out.close();
}
}
}
But you also don't need to close explicitly because PrintWriter
implements AutoCloseable
, so you can use Java 7's automatic resource management:
package practice.with.arrays.and.io;
import java.io.IOException;
import java.io.PrintWriter;
public class PracticeWithArraysAndIO {
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter("myFile.txt")) {
out.println("hello");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.