-1

I'm not able to access files with spaces in its name.

My Code:

String fileName = "This is my file.txt";
String path = "/home/myUsername/folder/";
String filePath = path + filename;
f = new BufferedInputStream(new FileInputStream(filePath));

I'm getting FileNotFoundException

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

2 Answers2

1

First thing there is a typo in parameter fileName:

String **fileName** = "This is my file.txt";
    String filePath = path + **filename**;

Here is the updated code with your example:

  String fileName = "This is my file.txt";
            String path = File.separator + "home" + File.separator + "myUsername" + File.separator + "folder" + File.separator;
            String filePath = path + fileName;
            BufferedInputStream f = new BufferedInputStream(new FileInputStream(filePath));

I am able to read the file with spaces in file name.

Using File.separator we let the code to replace the file separator based on OS.

Seshidhar G
  • 265
  • 1
  • 9
0
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class AccessMyFile {
    public static void main(String[] args) throws IOException {
        File file = new File("/home/This is my file.txt");
        System.out.println(file.exists());//true
        System.out.println(file.isFile());//true
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        while(bis.available()>0) {
            System.out.print((char)bis.read());
        }
    }//main
}//class

File: /home/This is my file.txt

Output:

hello world

Use java.io.File for checking if exists or not. Then you know your code is working or not.

Shaurya Manhar
  • 261
  • 1
  • 3
  • 5