Writing to txt file, Null pointer Exception [duplicate] - java

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.

Related

NullPointerException when trying to read file, same exact code worked before [duplicate]

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();
}
}

Getting file not found exception when I file does exist [duplicate]

This question already has an answer here:
File not found java
(1 answer)
Closed 2 years ago.
I have a java project in eclipse and have a method that reads information from a file. When I do a JUnit test on the method, it is unable to find the file even though it is in my working tree and I used the correct class path declaration.
Method to read file:
public static ArrayList<Issue> readIssuesFromFile(String filename) {
ArrayList<Issue> issues = new ArrayList<Issue>();
try {
Scanner sc = new Scanner(new FileInputStream(filename));
String text = "";
while(sc.hasNextLine()) {
text+= sc.nextLine();
text+= "\n";
}
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
JUnit Test:
public void testReadIssueFromFile() {
String test = "test-files/valid_file.txt";
try {
ArrayList<Issue> issues = IssueReader.readIssuesFromFile(testFile);
assertEquals(issues.get(0).getIssueId(), 0);
} catch (Exception e) {
fail(e.getMessage());
}
}
Working Tree:
->Project
->src
->.java file containing method
->test
->JUnit test file
->test-files
->txt file
According to your working tree i think your path should be:
../test-files/valid_file.txt
The path you used (test-files/valid_file.txt) means search in the folder of your JUnit file a folder named test-files and search inside this folder a file named valid_file.txt.
According to your working tree it's not the case. So you need .. to move to the above level where you can find the folder test-files.
If it still doesn't work, maybe try to debug you program by printing the paths that you have used like this:
try {
/* Here you can replace the period with another path like "test-files/valid_file.txt"
* to see the absolute path of it
*/
System.out.print(new java.io.File( "." ).getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}

Save a File on a specific path

i have the current code:
public void crearArchivo(String nombre) {
archivo = new File(nombre.replaceAll("\\s", "") + ".txt");
if (!archivo.exists()) {
try {
archivo.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void crearCarpeta(String nombreCarpeta){
File directorio = new File(nombreCarpeta);
directorio.mkdir();
}
public void crearArchivoDatos(String nombreArchivo, ArrayList<String>datos) {
crearArchivo(nombreArchivo);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(archivo));
for (int i = 0; i < datos.size(); i++) {
bw.write(datos.get(i));
}
bw.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
the first method create a file only if it doesnt exist and the second one create a folder finally the third method save the data my problem is that i want to save some files on the folder i created first how can i set a path to save those file there, also i have the problem that this little program will execute at diferent computers so the path will change for any computer
You can get paths of folders on any computer using System.getProperty(...) - for example System.getProperty("user.home") gives you the current user directory (from which you can get to the desktop and other folders), and System.getProperty("user.dir") gives you the path of the folder from which your program is executed.
Creating or modifying files in Java can be done with the Java 8 NIO.2 methods.
Here is a link to the Oracle documentation : https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
For your question, you have to declare a relative path, so it will be independent of the computer it will be executed on, rather than an absolute path, which begin on the root of the filesystem.

Writing to txt doc on new line Java [duplicate]

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().

Text File Writing Not Working

I have been experimenting with writing to text files for output instead of System.out.println(). When I try this, though, nothing seems to be written. What is the issue with my code?
try{
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("output.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
System.out.println("Frick, something broke. Sorry folks, go home.");
}
I just did a small change to your code by passing the path as the resources directory located in the root of my project. I was able to write to the file successfully.
Here is the updated code:
try {
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("./resources/test.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
ex.printStackTrace();
System.out.println("Frick, something broke. Sorry folks, go home.");
}

Categories

Resources