Reputation: 285
I am trying to read a file in java. The following is the code.
String str = ".\\SomeFileName";
File file = new File(str);
InputStream is = new FileInputStream(file.getPath());
A FileNotFoundException is thrown in last line. Can some one help?
Upvotes: 0
Views: 145
Reputation: 2456
THe program below is working fine, please first run it by just uncomment the commented statement and comment the InputStreamReader statements
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; public class FileRead { public static void main(String args[]){ try{ //String str = ".\\SomeFileName"; File file = new File(".\\file.csv"); // FileWriter writer=new FileWriter(file); //writer.write("it can writer"); //writer.flush(); InputStream is = new FileInputStream(file.getPath()); BufferedReader br=new BufferedReader(new InputStreamReader(is)); System.out.println(br.readLine()); }catch(Exception e){ e.printStackTrace(); } } }
I think YOu have problem in putting the file at correct location
Upvotes: 0
Reputation: 6062
Try by giving absolute path...Full directory path.
File file = new File("C:\\abc.txt");
and then test this also. str is a string having a file name
File file = new File(str);
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);
Upvotes: 0
Reputation: 18405
You can specify a file in two ways; either absolute, eg
String fileName1 = "c:\temp\myfile.txt"; \\For Windows
String fileName2 = "/home/qwerky/myfile.txt"; \\For Linux
or relative, eg
String fileName3 = "myfile.txt";
If you are using the relative path, then the path is relative to java's current working directory. You can find this by getting the file "." and priting the absolute path.
File cwd = new File(".");
System.out.println("Current working directory is " + cwd.getAbsolutePath());
Upvotes: 0
Reputation: 2185
You need to determine your current working directory. You can figure out you current working directory with this:
String curDir = System.getProperty("user.dir");
Upvotes: 2