This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am trying to get input from a JOptionPane and store what the user typed into a text file using the FileWriter class.To make sure that the input from what the user typed was being stored I wrote a system.out and what I typed in the JOptionPane appears. Unfortunately when I open the .txt file nothing I entered appears! By the way, the file path I entered is correct.
Here is my code. HELP ME!
String playername = JOptionPane.showInputDialog("What Will Be Your Character's Name?");
System.out.println(playername);
try {
FileWriter charectersname = new FileWriter("/Users/AlecStanton/Desktop/name.txt/");
BufferedWriter out = new BufferedWriter(charectersname);
out.write(playername);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Buffered writers will only write out when they're full or when they're being closed (hence the name Buffered).
So you can do this:
out.close();
which will flush the buffer and then close it. If you only wanted to flush it but keep it open for further writes (e.g. imagine you're writing a log file), you could do:
out.flush();
You'd likely want to do this when finishing up with such a resource. e.g.
BufferedWriter out = ...
try {
out.write(...);
}
catch (Exception e) {
// ..
}
finally {
out.close();
}
Or possibly using the try-with-resources constructs in Java 7, which (frankly) is more reliable to write code around.
The Java 7 version with the try() closing automatically.
try (BufferedWriter out = new BufferedWriter(
new FileWriter("/Users/AlecStanton/Desktop/name.txt"))) {
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
}
Mind the left-out / after .txt.
You should close your writer in a finally block.
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("/Users/AlecStanton/Desktop/name.txt/"));
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null){
out.close();
} else {
System.out.println("Buffer has not been initialized!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Related
For some reason my String is written partially by PrintWriter. As a result I am getting partial text in my file. Here's the method:
public void new_file_with_text(String text, String fname) {
File f = null;
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
out.print(text);
} catch (IOException e) {
e.printStackTrace();
}
}
Where I print text to a console, I can see that the data is all there, nothing is lost, but apparently part of text is lost when PrintWriter does its job... I am clueless..
You should always Writer#close your streams before you discard your opened streams. This will free some rather expensive system resources that your JVM must quire when opening a file on the file system. If you do not want to close your stream, you can use Writer#flush. This will make your changes visible on the file system without closing the stream. When closing the stream, all data is flushed implicitly.
Streams always buffer data in order to only write to the file system when there is enough data to be written. The stream flushes its data automatically every now and then when it in some way considers the data worth writing. Writing to the file system is an expensive operation (it costs time and system resources) and should therefore only be done if it really is necessary. Therefore, you need to flush your stream's cache manually, if you desire an immediate write.
In general, make sure that you always close streams since they use quite some system resources. Java has some mechanisms for closing streams on garbage collection but these mechanisms should only be seen as a last resort since streams can live for quite some time before they are actually garbage collected. Therefore, always use try {} finally {} to assure that streams get closed, even on exceptions after the opening of a stream. If you do not pay attention to this, you will end up with an IOException signaling that you have opened too many files.
You want to change your code like this:
public void new_file_with_text(String text, String fname) {
File f = null;
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
try {
out.print(text);
} finally {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try to use out.flush(); right after the line out.print(text);
Here is a proper way to write in a file :
public void new_file_with_text(String text, String fname) {
try (FileWriter f = new FileWriter(fname)) {
f.write(text);
f.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
I tested you code. You forgot to close the PrintWriter object i.e out.close
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
out.print(text);
out.close(); // <--------------
} catch (IOException e) {
System.out.println(e);
}
You must always close your streams (which will also flush them), in a finally block, or using the Java 7 try-with-resources facility:
PrintWriter out = null;
try {
...
}
finally {
if (out != null) {
out.close();
}
}
or
try (PrintWriter out = new PrintWriter(...)) {
...
}
If you don't close your streams, not only won't everything be flushed to the file, but at some time, your OS will be out of available file descriptors.
You should close your file:
PrintWriter out = new PrintWriter(f, "UTF-8");
try
{
out.print(text);
}
finally
{
try
{
out.close();
}
catch(Throwable t)
{
t.printStackTrace();
}
}
I am making a save/load feature for the settings in my application. Upon launching the program, it tries to find the file. If it fails, it tries to create a file with default settings (code below)
try (FileWriter fileWriter = new FileWriter(absolutePath))
{
fileWriter.write("theme=light\n");
fileWriter.write("resolution=1280x720\n");
fileWriter.write("printfps=false\n");
System.out.println("Reset settings");
load();
}
catch (FileNotFoundException e)
{
System.out.println("Settings File not found.");
}
catch (IOException e)
{
e.printStackTrace();
}
After it has written this, it goes on to load the file. (calling load() method)
In the load method, the application reads the contents of the file (code below).
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath)))
{
String line = bufferedReader.readLine();
System.out.println(line);
while(line != null)
{
if (line.contains("="))
{
String key = line;
String value = line;
while (key.contains("="))
{
key = key.substring(0, key.length() - 1);
}
while (value.contains("="))
{
value = value.substring(1);
}
settings.put(key, value);
}
System.out.println(line);
line = bufferedReader.readLine();
}
System.out.println(settings);
}
However, it returns that the file is empty. After messing with breakpoints, I can confirm that the file is indeed not updated at that point. The rather weird thing is that if I pause the application at a later time, the file seems to contain the text that was written to it, even though the file is not touched later in the program.
This makes me believe that it takes some time for the file to update, thus not updating in time for the load() method. Is this correct, or am I missing something? And is there a workaround?
All help is appreciated :)
You're calling load() before you actually saved the file.
To save the file, call fileWriter.close() or just move the load() call out of the try-with-resource block with the FileWriter:
try (FileWriter fileWriter = new FileWriter(absolutePath))
{
fileWriter.write("theme=light\n");
fileWriter.write("resolution=1280x720\n");
fileWriter.write("printfps=false\n");
}
catch (FileNotFoundException e)
{
System.out.println("Settings File not found.");
}
catch (IOException e)
{
e.printStackTrace();
}
// FileWriter closed now and the file contents saved
System.out.println("Reset settings");
load();
I put the declaration in the while loop, and the program would not running and also does not return any error. I suspect the while loop become an infinite loop.
try
{
while (true)
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
But if I put the declaration of input stream out of the while loop, the program runs successfully. Can someone explain why this happens?
try
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
while (true)
{
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
You're reopening your file on every iteration through the loop, which means you are only ever reading the first object from the file. But you're reading the same object over and over again.
As well as opening your file only once, you really should try to detect the end of file without throwing an exception. As a matter of style, exceptions should be thrown when things go wrong, not as a matter of course.
Now I realize that in each iteration, I reopen the input stream, so the loop would not reach to the end of the file, and it becomes infinite.
I am running another jar with this code:
(I am updating a gui in some parts , so dont feel confused.)I get an IO Exception (Stream Closed) here:
if((line = readr.readLine()) != null){
Thats the full code:
if(!data.serverStarted()){
try{
data.updateConsole("Starting server!");
String fileDir = data.dir + File.separator + "craftbukkit.jar";
Process proc = Runtime.getRuntime().exec("java -Xmx2048M -jar "+"craftbukkit.jar"+" -o true --nojline");
data.setOutputStream(proc.getOutputStream());
InputStream is = proc.getErrorStream();
}catch(IOException ex){
ex.printStackTrace();
}
BufferedReader readr = new BufferedReader(new InputStreamReader(is));
data.setServerStarted(true);
String line;
while(data.serverStarted()){
try {
if((line = readr.readLine()) != null){
data.updateConsole(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
readr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
data.updateConsole("You have already started your server!");
}
You have a while loop that closes readr on every pass. The next time it gets to the try block, readr is closed. Perhaps you intended to put the try/catch block around the while loop?
You are closing the reader inside the loop that reads from it. You need to close it outside of the loop:
try {
String line;
while (data.serverStarted() && ((line = readr.readLine()) != null)) {
try {
data.updateConsole(line);
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
readr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I am surprised that this code even compiles.
You declare the actual InputStream is inside the try/catch at the beginning, but that makes it only visible inside that block. So whatever you give to the BufferedReader a few lines below is something else and most likely not what you think it is.
In addition your while(data.serverStarted()) does not check if the stream is still open, and later you only use a single if check (again with no check if the stream is open), so you'll only read one single line at best.
I have a feeling that you had a bad OutOfCoffeeException while writing this code. ;)
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am trying to get input from a JOptionPane and store what the user typed into a text file using the FileWriter class.To make sure that the input from what the user typed was being stored I wrote a system.out and what I typed in the JOptionPane appears. Unfortunately when I open the .txt file nothing I entered appears! By the way, the file path I entered is correct.
Here is my code. HELP ME!
String playername = JOptionPane.showInputDialog("What Will Be Your Character's Name?");
System.out.println(playername);
try {
FileWriter charectersname = new FileWriter("/Users/AlecStanton/Desktop/name.txt/");
BufferedWriter out = new BufferedWriter(charectersname);
out.write(playername);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Buffered writers will only write out when they're full or when they're being closed (hence the name Buffered).
So you can do this:
out.close();
which will flush the buffer and then close it. If you only wanted to flush it but keep it open for further writes (e.g. imagine you're writing a log file), you could do:
out.flush();
You'd likely want to do this when finishing up with such a resource. e.g.
BufferedWriter out = ...
try {
out.write(...);
}
catch (Exception e) {
// ..
}
finally {
out.close();
}
Or possibly using the try-with-resources constructs in Java 7, which (frankly) is more reliable to write code around.
The Java 7 version with the try() closing automatically.
try (BufferedWriter out = new BufferedWriter(
new FileWriter("/Users/AlecStanton/Desktop/name.txt"))) {
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
}
Mind the left-out / after .txt.
You should close your writer in a finally block.
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("/Users/AlecStanton/Desktop/name.txt/"));
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null){
out.close();
} else {
System.out.println("Buffer has not been initialized!");
}
} catch (IOException e) {
e.printStackTrace();
}
}