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();
}
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 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.
This is the code I use when I try to read some specific text in a *.txt file:
public void readFromFile(String filename, JTable table) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String a,b,c,d;
for(int i=0; i<3; i++)
{
a = bufferedReader.readLine();
b = bufferedReader.readLine();
c = bufferedReader.readLine();
d = bufferedReader.readLine();
table.setValueAt(a, i, 0);
table.setValueAt(b, i, 1);
table.setValueAt(c, i, 2);
table.setValueAt(d, i, 3);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the reader
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
And it is called in this way:
readFromFile("C:/data/datafile.txt", table1)
The problem is the following: the 1st time I open the program the *.txt file I'm going to read does not exist, so I thought I could use the function exists(). I have no idea about what to do, but I tried this:
if(("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1)
}
It is not working because NetBeans gives me a lot of errors. How could I fix this?
String has no method named exists() (and even if it did it would not do what you require), which will be the cause of the errors reported by the IDE.
Create an instance of File and invoke exists() on the File instance:
if (new File("C:/data/datafile.txt").exists())
{
}
Note: This answer use classes that aren't available on a version less than Java 7.
The method exists() for the object String doesn't exist. See the String documentation for more information. If you want to check if a file exist base on a path you should use Path with Files to verify the existence of the file.
Path file = Paths.get("C:/data/datafile.txt");
if(Files.exists(file)){
//your code here
}
Some tutorial about the Path class : Oracle tutorial
And a blog post about How to manipulate files in Java 7
Suggestion for your code:
I'll point to you the tutorial about try-with-resources as it could be useful to you. I also want to bring your attention on Files#readAllLines as it could help you reduce the code for the reading operation. Based on this method you could use a for-each loop to add all the lines of the file on your JTable.
you can use this code to check if the file exist
Using java.io.File
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
You need to give it an actual File object. You're on the right track, but NetBeans (and java, for that matter) has no idea what '("C:/data/datafile.txt")' is.
What you probably wanted to do there was create a java.io.File object using that string as the argument, like so:
File file = new File ("C:/data/datafile.txt");
if (file.exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
Also, you were missing a semicolon at the end of the readFromFile call. Im not sure if that is just a typo, but you'll want to check on that as well.
If you know you're only ever using this File object just to check existence, you could also do:
if (new File("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
If you want to ensure that you can read from the file, it might even be appropriate to use:
if(new File("C:/data/datafile.txt").canRead()){
...
}
as a condition, in order to verify that the file exists and you have sufficient permissions to read from the file.
Link to canRead() javadoc
I'm trying to read a file that exists in the following location of my Eclipse java project:
Tester -> src -> threads -> ReadFile.java
This is the code used:
public class Tester {
public static void main(String[] args) {
ReadFile[] readers;
readers = new ReadFile[3];
for (int intLoopCounter = 0; intLoopCounter < 3; intLoopCounter++) {
readers[intLoopCounter] =
new ReadFile("ReadFile.java", intLoopCounter);
System.out.println("Doing thread number: " + (intLoopCounter + 1));
}
}
Can you tell me what to add to:
new ReadFile("ReadFile.java"
so the file can be read?
There is a buffered reader in the ReadFile.java class file. I'm experimenting with this just to see if I can read the ReafFile.java file and show the results to the console.
Here is the code that is throwing the error from ReadFile.java:
public ReadFile(String filename, int i) {
id = i;
try {
input = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Problem occured: " + e.getMessage());
} // catch
} // Constructor
Assuming that Tester is your project root directory, your path to the file should be "src/threads/ReadFile.java". If the file trully exists it will be found.
You need to modify the path in the call to ReadFile to include a full path, a path anchored by your user directory, or a path relative to the directory in which Eclipse runs your test program.
For example, if your project is located in /Users/myuser/projects/Tester/src/threads, you can use this line:
new ReadFile("/Users/myuser/projects/Tester/src/threads/ReadFile.java", intLoopCounter)