Error reading path in java - java

I am trying to read a text file in java, but I am having this annoying FILENOTFOUND EXCEPTION:
try {
BufferedReader br = new BufferedReader (new FileReader("/home/asad/workspace/MyFirstProject/HelloWorld.txt"));
while ((reader = br.readLine())!= null);
System.out.print(reader);
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is the simplest code and should read a text file name HelloWorld from the specified path, should store it in the string "reader" and displays its output on the console, but the compiler is having problems locating the file.
Strange thing is, I have tried looking for the file path using getCanonicalPath() and it is specifying to the same path I have been looking, but the compiler is not finding the file. Any help?

Try to check this test before your code:
File file = new File("/home/asad/workspace/MyFirstProject/HelloWorld.txt");
if( file.exists() ) {
System.out.println("File exists!");
} else {
System.out.println("File not existst!");
}
if you get FileNotFoundException, file isn't in this localization or file name is incorrect.

i just spotted the problem of my code,
by omitting the .txt from the path printed the solution.
i changed the code from
BufferedReader br = new BufferedReader (new FileReader("/home/asad/workspace/MyFirstProject/HelloWorld.txt"));
to
BufferedReader br = new BufferedReader (new FileReader("/home/asad/workspace/MyFirstProject/HelloWorld"));
and boosh the console printed the text stored in the file.

In the while-loop the empty statement ; was executed till the end of file.
if ((reader = br.readLine())!= null) { // Not ;
System.out.println(reader); // Not print, as reader has "\r\n" removed
}
br.close();
Using if instead of the usual while to retrieve the first line only.
The FileNotFoundException is probably true. To find the typo you can do in a terminal:
cat /home/asad/workspace/MyFirstProject/HelloWorld.txt
ls /home/asad/workspace/MyFirstProject
ls /home/asad/workspace
Most likely it should have been "MyfirstProject" or so.

Related

FileNotFound exception but there is a file (Java Eclipse)

I cant get rid of this FileNotFound error even though the file exists. Any ideas? (There are hundreds of lines of code so im just going to paste the chunk around the error, if this is an issue I can post more)
// method start
System.out.println(System.getProperty("user.dir"));
File names = new File("src/guiProject/nameList");
System.out.println(names.getAbsolutePath());
// !!!! V ERROR OCCURS HERE V !!!!
BufferedReader br = new BufferedReader(new FileReader(names));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String allNames = sb.toString();
userListArea.setText(allNames);
} catch (IOException o) {
o.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//method end
Probably your Windows does not show file extensions; nameList.txt?
Otherwise the working directory is not in the project directory with subdirectory src.
A FileReader uses the default Charset, so the file is not portable. If you run the application on another platform then the developer's, the encoding is wrong.
Best use UTF-8, full Unicode.
Then the reading strips the line ending:
while (line != null) {
sb.append(line).append("\r\n");
line = br.readLine();
}
You could do:
Path names = Paths.get("src/guiProject/nameList.txt"); // File
Path names = Paths.get(
MyClass.class.getResource("/guiProject/nameList.txt").toURI()); // Resource
String allNames = new String(Files.readAllBytes(names), StandardCharsets.UTF_8);
userListArea.setText(allNames);
If it is a read-only file, stored in the application jar, it is a resource rather than a disk File.
Maybe you are not in the folder you think.
Create a file with a dummy name and get the absolute path of this file, this way you can doublecheck you are where you think you really are.

Cannot delete file after performing operations

Unable to delete files even after closing the corresponding readers and writers.
Permissions are present on the files
file.delete() returns false
my code
main(){
try{
File file=new File(path);// Path where the file is present
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
FileWriter writer = new FileWriter(pathOther);
BufferedWriter wr = new BufferedWriter(writer);
// Readers and writers for i/o operations
while((String str=br.readLine())!=null){
wr.write(str); // Copying to another file
}
}catch(Exception e){}
finally{
reader.close(); //close reader
writer.close(); //close writer
file.delete(); //This returns false
}
My guess as to what is going on is that you close the FileInputStream but leave the BufferedReader open, which leaves something holding on to the file handle. Then, when you try to delete the file, it returns false because something else has a handle on it.
Try the following code:
File file = new File(path);
try {
br = new BufferedReader(new FileReader(file));
// use the reader ...
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// now close the file
file.delete();
Update:
While testing the above code I noticed something else which could also cause the observations you were seeing. If the file at path does not exist, then logically calling file.delete will also fail for this reason. So you should make sure that the file actually exists before trying to delete it. You can call file.exists() to check for this.
First, you should close the BufferedReader instead of the FileReader (the BufferedReader will in turn call close() on the FileReader):
So instead of:
reader.close(); //close reader
do:
br.close();
(and leave out the complete redundant comment).
Also, since File.delete() simply returns a Boolean and doesn't tell you why it failed, you can get more information by calling Files.delete instead:
try {
Files.delete(file.toPath());
} catch (IOException e) {
// e now contains information about why it can't delete.
}
Nothing will work call System.gc();

Using a Dynamic path for a csv file

I have a program that saves on a file. The current code is set for the file to save on a specific path, but when I run the program from a different computer the program doesn't work and I need to change the path everytime.
public CreateCustomer() {
initComponents();
ArrayList<String> ConsIDList = new ArrayList<String>();
String csvFileToRead = "E:\\ryan_assignment_sit2\\ConsID\\consID.csv"; // Reads the CSV File.
BufferedReader br = null; // Creates a buffer reader.
String line = "";
String splitBy = ","; // Reader Delimiter
try {
br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
Scanner reader = new Scanner(System.in);
while ((line = br.readLine()) != null) { //While there is a line to read.
reader = new Scanner(line);
reader.useDelimiter(splitBy);
while (reader.hasNext()) { // While there is a next value (token).
ConsIDList.add(reader.next());
}
}
} catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
exception.printStackTrace();
} catch (IOException exception) { // Input/Output exception
exception.printStackTrace();
} finally {
if (br != null) {
try {
br.close(); // Close the Scanner.
} catch (IOException exception) {
exception.printStackTrace();
}
}
I placed the file in the a subfolder in the program with the name ConsID and I tried changing the path file to
String csvFileToRead = "..\\ConsID\\consID.csv";
But the file can't be read from the program.
String csvFileToRead = "E:\ryan_assignment_sit2\ConsID\consID.csv";
The above path will only be applicable to windows. If you execute the program in linux environment you will get an Filenotfoundexception. Eventhough you change the file, again you are hardcoding the file path.
Better you can get it as runtime parameters so that the program will be executed irrespective of OS.
If you are running you program from command line then you can place the csv file in your classpath (root folder where the class files are generated) and refer to it as below:
BufferedReader br = new BufferedReader(ClassLoader.getResourceAsStream("consID.csv"));

Reading unicode characters from csv file

I have a csv file which contains words in english followed by their Hindi translation. I am trying to read the csv file and do some further processing with it. The csv file looks like so:
English,,Hindi,,,
,,,,,
Cat,,बिल्ली,,,
Rat,,चूहा,,,
abandon,,छोड़ देना,त्याग देना,लापरवाही की स्वतन्त्रता,जाने देना
I am trying to read the csv file line by line and display what has been written. The code snippet (Java) is as follows:
//Step 2. Read csv file and get the string.
FileInputStream fis = null;
BufferedReader br = null;
try {
fis = new FileInputStream(new File(csvFile));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
boolean startSeen = true;
if(fis != null) {
try {
br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
System.out.print("Unsupported encoding");
}
String line = null;
if(br != null) {
try {
while((line = br.readLine()) != null) {
if(line.contains("English") == true) {
startSeen = true;
}
if((startSeen == true) && (line != null)) {
StringBuffer sbuf = new StringBuffer();
//Step 3. Parse the line.
sbuf.append(line);
System.out.println(sbuf.toString());
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
However, the following output is what I get:
English,,Hindi,,,
,,,,,
Cat,,??????,,,
Rat,,????,,,
abandon,,???? ????,????? ????,???????? ?? ???????????,???? ????
My Java is not that great and though I have gone through a number of posts on SO, I need more help in figuring out the exact cause of this problem.
For reading text file it is better to use character stream e.g by using java.util.Scanner directly instead of FileInputStream. About encoding you have to make sure first that the text file that you want to read is saved as 'UTF-8' and not otherwise. I also notice in my system, I have to save my java source file as 'UTF-8' as well to make it shown hindi char properly.
However I want to suggest simpler way to read csv file as follow:
Scanner scan = new Scanner(new File(csvFile));
while(scan.hasNext()){
System.out.println(scan.nextLine());
}
I think your console cannot show Hindi chars. Try
System.out.println("Cat,,बिल्ली,,,");
to test
So as discussed in above answers; solutions it is TWO steps
1) Save your txt file as UTF-8
2) Change the property of your Java code to use UTF-8
In Eclipse; right click on Java file;
Properties -> Resurces -> Text File Encoding -> Other -> UTF-8
Refer screenshot given on
http://howtodoinjava.com/2012/11/27/how-to-compile-and-run-java-program-written-in-another-language/

java - buffered readed readline() gives null as end of file but no way to use that null

Is there a way to check whether a file was correctly written, I mean if there is an EOF at the end?
I'm asking that because I have a program that takes some file, merge them in a very big file and then use it to get statistics from it.
The point is that the second part never ends because it doesn't recognize the end of file.
The relevant parts of the code are the following:
(please do not ask for the whole code as I cannot post for important reasons)
FileWriter file=null;
PrintWriter pw = null;
String pathToRead=null;
InputStreamReader isr = null;
BufferedReader br = null ;
FileInputStream fis = null ;
TestJFileChooser d=new TestJFileChooser();
int c=1;
String line=null;
....
//here i select the files
selectedFile=new File(pathToRead);
//here I get one buffer reader for each file got with listFiles()
for(File file_sel:app){
if (file_sel.getName().startsWith("gtou")){
System.out.println(file_sel.getName());
fis = null;
try {
fis = new FileInputStream(file_sel);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
isr=new InputStreamReader(fis);
br=new BufferedReader(isr);
map.put(i, br);
num_file++;
i++;
}
}
//then I select the output file and open a print writer for it
fileToWrite=new File(pathToRead);
try {
file = new FileWriter(fileToWrite);
pw= new PrintWriter(file);
} catch (IOException e1) {
e1.printStackTrace();
}
//merging part
....
line=br.readLine();
while(line!=null){
System.out.println("line is:"+line);
....
line=br.readLine();
}
//end of merging ....
pw.flush();
pw.close();
try {
if (file!=null) file.close();
fis.close();
isr.close();
br.close();
for(int fi=0;fi<num_file;fi++){
br2=map.get(fi);
br2.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
so.kill();
Runtime r=Runtime.getRuntime();
r.gc();
//this is a popup that comes out
GlitchSquad gli=new GlitchSquad("Completed");
the problem is that as output I get:
line is: null ;
line is: null ;
line is: null ;
etc
And never get to "completed" popup =(
I cannot understand what is exactly that null because the control line!=null doesn't work.
I also tried to use that null as a string ..but nothing..
I thought that was a problem in how I close the streams but now the code seems correct to me ..but still no way to stop it..
Suggestion?
Thanks in advance!
p.s. it is a summarized version in order to focus on the streams.. variables are correctly declared and the same is for imports etc
edit: code updated
EOF is EOF. There is no more data. Unless you have an expected EOF mark within the file, or a self-describing protocol that tells you where the EOF mark should be, there is no way to determine whether the file was completely written.
I don't know if it will solve your problem, but I'd be using this code instead:
try {
fis = new FileInputStream(file_sel);
isr=new InputStreamReader(fis);
br=new BufferedReader(isr);
map.put(num_file++, br);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Otherwise there may be uncaught "NullPointer"-exceptions or strange BufferedReaders in your "map". ( I don't right now know how new InputStreamReader(null) will behave.)
It looks like i and num_file have always equal values, so just drop i. Or use a LinkedList and drop both.
If there's not a special merging that you have to do, I'd just do it like this:
OutputStream os;
try {
os = new FileOuputStream(outfile);
} catch (FileNotFoundException e) {
os = null;
e.printStackTrace();
}
if (os != null) {
for(File file_sel:app) {
if (file_sel.getName().startsWith("gtou")) {
System.out.println(file_sel.getName());
InputStream is = null;
try {
is = new FileInputStream(file_sel);
byte[] buffer = new byte[1024];
int readBytes = 0;
while ((readBytes = is.read(buffer)) > 0) {
os.write(buffer, 0, readBytes);
}
fos.flush();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
If you read files with different encodings, you will have to modify at least the reading of course.
If it doesn't work, I'd suggest you build a "summarized" and runable sample program.
The core of your question is this code:
BufferedReader br = ...
String line = br.readLine();
while (line != null) {
System.out.println("line is:" + line);
...
line = br.readLine();
}
You say that this repeatedly outputs this:
line is: null ;
line is: null ;
(Notice the " ;" on the end!!!)
The only way that can happen is if the file you are reading contains at least one line that look like this:
null ;
Indeed, unless the "..." code includes a continue statement, there must must be lots of those lines in the input file.
Is there a way to check whether a file was correctly written?
Yea. Look at it using a text editor and/or check its file size.
I mean if there is an EOF at the end?
In modern file systems, EOF is a position not a marker. Specifically it is the position after the last byte of the file. So it is logically impossible for a file to not have an EOF. (You'd have to have a file that is infinite in length for there to be no EOF.)

Categories