Search code examples
javafileioexception

Java create file if does not exist


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)

Solution

  • 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