While executing the program I am getting FileNotFoundException
java.io.FileNotFoundException: Shyam\src\sam\examles\TextFile.txt (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at sam.examples.ReadingFile.main(ReadingFile.java:9)
below is my java program ReadingFile.java
package sam.examples;
import java.io.*;
public class ReadingFile {
public static void main(String[] args) {
try {
FileInputStream fstream = new FileInputStream("C:\\Documents and Settings\flower\workspace\Shyam\src\sam\examples\TextFile.txt");
DataInputStream dis = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String str;
while ((str = br.readLine()) != null) {
System.err.println(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The file is in the same path where my java program is there as below
Shyam
|- src
|-sam.examples
|-ReadingFile.java
|-TextFile.txt
Could you please help us in resolving this
You probably need to escape the backslashes in the file path. You've done it for the first one but not the others.
FileInputStream fstream = new FileInputStream("C:\\Documents and Settings\\flower\\workspace\\Shyam\\src\\sam\\examples\\TextFile.txt");
Your exceptions tells that the path you have specified is different. Either use the whole, absolute path (as you have shown in the code, but perhaps did not execute), or use classpath resources.
getClass().getResourceAsStream("Text.txt")
. This looks for the file in the package where the current class is. You can also use classpath-absolute paths, like .getResourceAsStream("/sam/examples/TextFile.txt")
a debugging tip:
refactor this line:
FileInputStream fstream = new FileInputStream("C:\\Documents and Settings\flower\workspace\Shyam\src\sam\examples\TextFile.txt");
to
File file = new File("C:\\Documents and Settings\flower\workspace\Shyam\src\sam\examples\TextFile.txt");
System.out.println(file.getAbsolutePath());
FileInputStream fstream = new FileInputStream(file);
Then see if the output really is that file.
try these..
FileInputStream fstream= new FileInputStream(new File("C:\\Documents and Settings\\flower\\workspace\\Shyam\\src\\sam\\examples\\TextFile.txt"));
or
FileReader fstream = new FileReader(new File("C:\\Documents and Settings\\flower\\workspace\\Shyam\\src\\sam\\examples\\TextFile.txt"));
BufferedReader in = new BufferedReader(fstream);
You never need to use backslashes in filenames in Java. Change them all to forward slashes and get rid of the double ones.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.