This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 4 years ago.
public void writePlayerTurnActions(String action){
File file = new File(this.playerFileName);
try {
FileWriter writer = new FileWriter(this.playerFileName);
if(!file.exists()) {
file.createNewFile();
}
writer.write(action + "\n");
writer.close();
} catch (IOException e) {
System.out.println("Error writing to player output file");
}
}
Here is the method im using to keep updating a file depending on what occurs during the execution of the program. Im calling it by
instance.writePlayerTurnActions("1");
instance.writePlayerTurnActions("2");
instance.writePlayerTurnActions("3");
When running this code the file only contains a 3... and not 1, 2, 3 on seperate lines.
Any help appreciated as i'm so confused as to whats going wrong...
you should not create a new FileWriter instance each time you want to write something (not only because of this issue, it's also very bad performance wise). Instead, keep one globally and instead of calling writer.close() when you're done writing your current String to the file, call writer.flush().
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last month.
I wanted to run a Java program I wrote two years ago. It needs two files as command line parameters and reads them. This program has worked great before and as it was a school project it went through many tests to make sure everything was working correctly. I downloaded the project from my submission to make sure I had the same version. Only thing this version lacked was the files to read because we were asked not to include them and rather use a path so they don't accidentally get tracked by version control. I added the files to the same directory as the main java file. When I run the program I get:
Welcome to "Name of school project"
Exception in thread "main" java.lang.NullPointerException
at practice.collection.Collection.download(Collection.java:100)
at practice.UI.UI.mainLoop(UI.java:63)
at mainFile.main(mainFile.java:60)
This is what download method in Collection looks like:
public void download(String fileName) {
Scanner fileReader = null;
try {
File file = new File(fileName);
fileReader = new Scanner(file);
while (fileReader.hasNextLine()) {
***reads lines and does some sorting***
}
fileReader.close();
}
catch (FileNotFoundException | NumberFormatException e) {
fileReader.close(); ***this is line 100***
System.out.println("Missing file!");
System.out.println("Program terminated.");
System.exit(0);
}
}
I have also made sure the files to be downloaded are the same as before, they are not empty and are being called with correct spelling, in correct order. Like this: java mainFile first_file.txt second_file.txt. Why is the program not finding the files like before?
I did check out What is a NullPointerException, and how do I fix it? but does not answer my question. I assume I get the exception because my program can't find the file and is thus referring to a file object with null value. I am trying to figure out why the file can't be found and read. I think I should be able to fix this problem without touching the code. The program behaves the same way regardless of if the files have been included.
Suggested changes for troubleshooting the underlying problem:
public void download(String fileName) {
System.out.println("fileName=" + fileName + "...");
System.out.println("current directory=" + System.getProperty("user.dir"));
Scanner fileReader = null;
try {
File file = new File(fileName);
fileReader = new Scanner(file);
while (fileReader.hasNextLine()) {
***reads lines and does some sorting***
}
fileReader.close();
}
catch (FileNotFoundException | NumberFormatException e) {
System.out.println(e); // Better to print the entire exception
//System.out.println("Missing file!"); // Q: What about NumberFormatException?
System.out.println("Program terminated.");
System.exit(0);
}
finally {
// This assumes your app won't be using the scanner again
if (fileReader != null)
fileReader.close();
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am trying to write to a csv file however everytime i get a null pointer exception. The data i wanted written to the csv file is being written but i get the error and i cant figure out why.
public static void writeCsvFile() {
FileWriter fw = null;
VendingMachine vm = new VendingMachine("Conall", 10);
try {
fw = new FileWriter("stock.txt");
//fw.append("ID");
for (VendItem item : stock) {
fw.append(String.valueOf(item.getId()));
fw.append(",");
fw.append(item.getName());
fw.append(",");
fw.append(String.valueOf(item.getPrice()));
fw.append(",");
fw.append(String.valueOf(item.getPrice()));
fw.append("\n");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fw.flush();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My file has the following in it:
1,Coke,0.7,0.7
2,Fanta,0.6,0.6
3,Galaxy,1.2,1.2
4,Snickers,1.0,1.0
5,Dairy Milk,1.3,1.3
6,Kinder,1.3,1.3
How can i fix the null pointer error as it seems to be working as i am looking it to, i.e writing the files in my stock to this file.
Thanks for any help
You did not specify a file path for your file "stock.txt". Your program will only know where "stock.txt" is if it is located in your project folder, not your source folder. If your file is somewhere else- in your documents folder, for example, you should specify an absolute or relative file path.
I was working on my assignment and found that the textfile which I suppose to write data to,
Data cannot be written twice to it once I close the program and run again. Here is the code
public static void writeFile() {
try {
PrintWriter writeFile = new PrintWriter(file);
writeFile.print(buttonC1.getText()+"\t"+
stdname.getText()+"\t"+mtcnum.getText()+"\t"+cid.getText()+
"\t"+spvname.getText()+"\r\n123");
writeFile.close();
}catch(Exception e){
e.printStackTrace();
}
}
How is "file" created? Is a stacktrace printed? In the catch block, print e.getMessage().
Try this:
FileWriter writer = new FileWriter("test.txt");
try(PrintWriter printWriter = new PrintWriter(writer)){
printWriter.write("Happy days are here again!");
}
After the above works, add in your content one step at a time. It is possible one of those elements is causing an issue, like a NullPointerException.
This question already has answers here:
Read text file in google GWT?
(2 answers)
Closed 7 years ago.
I'm writing an application for displaying chrats. I'm using GWT Highcharts (by Moxie Group) to display the results. I add a random number to the chart and it works without a problem.
But I want to load numbers from a text file. I just want to read the contents of a file and put it on the array or something similar. How can I do this in Java?
You can use a small program as like the below to achieve that:
You may have to change the logic to read elements the way you want it for your GWT highcharts!
public class ReadATextFile {
public static void main(String[] args) {
try (RandomAccessFile readFile = new RandomAccessFile("C:\\Test.txt", "r");) {
int EOF = (int) readFile.length();
System.out.println("Length of the file is (" + EOF + ") bytes");
//Considering to read the first 150 bytes out of 168 bytes on the file
readFile.seek(0);
byte[] bytes = new byte[EOF];
readFile.readFully(bytes);
readFile.close();
System.out.println(new String(bytes));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Where the Test.txt file's contents is something like this:
1 2 3 4
5 6 7 8
9 10 11
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I have a simple program that needs to write a few lines of string to a file using FileWriter and BufferedWriter. It already reads the (in this case) exact same data from the file, it stores it in runtime memory, but it outright refuses to write it and I have no idea why. Usually I'd try to debug it and see what's happening but I have no idea what I'm looking for.
Here is my code:
public void close () {
FileWriter output = null;
BufferedWriter fileOut = null;
// I use the exact same method to read from file so this should work
// this.prajituri :: ArrayList
// toString is #Override
try {
output = new FileWriter(this.fileName);
fileOut = new BufferedWriter(output);
for (int i = 0; i < this.prajituri.size(); i++) {
fileOut.write(prajituri.get(i).toString());
System.out.println(prajituri.get(i).toString());
fileOut.newLine();
}
} catch (IOException ioe) {
System.out.println("Output error: " + ioe);
} finally {
if (fileOut != null)
fileOut = null;
if (output != null)
output = null;
}
}
Just in case, here is my toString:
#Override
public String toString () {
return this.name + ";" + this.weight + ";" + this.price;
}
Every time I try to write to file, it gives me an empty file. Am I doing something wrong ?
I checked and this.prajituri is actually good (has all the data it should have)
And I use the System.out.println(prajituri.get(i).toString()) to check what it Should write and that is OK also. Yet it writes nothing.
you have to close your BufferedWriter fileOut.close()
To write to disk immediately:
output.flush();
When done:
output.close();
close( ) includes flush( )
You need to flush the stream to write it to disk.
flush in java.io.FileWriter
You should close the stream properly by calling fileout.close() (which will internally call the flush anyway).
You have to flush/ close your stream. If you're using Java SE 7, the easiest way is to use the new Automatic Resource Management feature:
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html