4

In my function I want to read a text file. If file does not exists it will be created. I want to use relative path so if i have .jar, file will be created in the exact same dir. I have tried this. This is my function and variable fName is set to test.txt

    private static String readFile(String fName) {
    String noDiacText;
    StringBuilder sb = new StringBuilder();
    try {
        File f = new File(fName, "UTF8");
        if(!f.exists()){
            f.getParentFile().mkdirs();
            f.createNewFile();
        }

        FileReader reader = new FileReader(fName);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fName), "UTF8"));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);

        }
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }


    return sb.toString();
}

I am getting an error at f.createNewFile(); it says

java.io.IOException:  System cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at main.zadanie3.readFile(zadanie3.java:92)
Community
  • 1
  • 1
tprieboj
  • 1,680
  • 6
  • 31
  • 54
  • Add a println or something and debug what the path looks like. Could you also say which line of the function is throwing the exception. – Reinard Nov 07 '15 at 11:13
  • If you use Java 7+ you should consider using java.nio.file instead – fge Nov 07 '15 at 11:28
  • Why? What good is an empty file to you? And an empty String? Just catch `FileNotFoundException,` or better still let it be thrown. – user207421 Nov 07 '15 at 11:57

2 Answers2

7

The problem is that

File f = new File(fName, "UTF8");

Doesn't set the file encoding to UTF8. Instead, the second argument is the child path, which has nothing to do with encoding; the first is the parent path.

So what you wanted is actually:

File f = new File("C:\\Parent", "testfile.txt");

or just:

File f = new File(fullFilePathName);

Without the second argument

Bon
  • 3,073
  • 5
  • 21
  • 40
1

Use mkdirs() --plural-- to create all missing parts of the path.

File f = new File("/many/parts/path");
f.mkdirs();

Note that 'mkdir()' --singular-- only creates the list part of the path, if possible.

Shoham
  • 1,079
  • 1
  • 12
  • 17