Reputation: 5446
I have coded the following for reading a txt in Java:
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String name;
String line;
System.out.println("Input file name");
Scanner inp=new Scanner(System.in);
name=inp.nextLine();
FileReader file=new FileReader(name);
BufferedReader br=new BufferedReader(new FileReader(name));
while((line=br.readLine())!=null){
System.out.println(br.readLine());
}
br.close();
}
I have a txt file that is under the same folder of my java code, its name is data.txt (which contains a list of numbers line by line), the problem that I got is that when I run this I got the following message:
Exception in thread "main" java.io.FileNotFoundException: data.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
where is the mistake? also how I can surround it with a try catch block in case the file does not exist?
I have put the System.out.println(new File(name).getAbsoluteFile);
and it appears all the path thru data.txt, but I want to point by default to my current folder; should I use Scanner
?
Upvotes: 0
Views: 5472
Reputation: 2973
If youre using a scanner, you need to use the File
Scanner inp=new Scanner(System.in);
name=inp.nextLine();
File file = new File(name);
if(file.exists()) {
try {
FileReader file=new FileReader(name);
BufferedReader br=new BufferedReader(new FileReader(name));
while((line=br.readLine())!=null){
System.out.println(br.readLine());
}
br.close();
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
that should help, hope it does :)
Upvotes: 0
Reputation: 208944
If you want to use the relative file name and you're running from an IDE like netbeans or eclipse, you file structure should look something like this
ProjectRoot
file.txt
src
build
file.txt
being the relative path you're using. The IDE will first search the Project root for the file if no other directories are specified in the file path.
Upvotes: 4