superfine123 superfine123 - 2 years ago 99
Java Question

file not found exception for reading contents of file

I am trying to read contents from file, but I am getting file not found exception.

Please help me out. I am using below code.

File f = new File("C:/sample/welcome.txt"); //working
System.out.println("File path ="+f.getPath());
System.out.println("File name = "+f.getName());
System.out.println("File size = "+f.length());
String ret = "";

HttpURLConnection connection = null;

try {

int size = (int) f.getName().length();
byte[] data = new byte[size];
String _contrainerName1 ="/development";
// String content = new String("This is my first upload to dropbox");
//String fileName ="test17.txt";

try {
InputStream inputStream = new FileInputStream(f.getName());

if ( inputStream != null ) {
DataInputStream in1 = new DataInputStream(inputStream);
// InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in1));

String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();

while ( (receiveString = bufferedReader.readLine()) != null ) {

ret = stringBuilder.toString();
} catch (FileNotFoundException e) {
System.out.println("login activity");

} catch (IOException e) {
System.out.println("login activity");

Answer Source

If you're trying to read a file in a Windows file system, you should use double backlash:

  File f = new File("C:\\sample\\welcome.txt");

Also, you can instantiate the FileInputStream passing directly the File object

  InputStream inputStream =  new FileInputStream(f);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download