Java create file if does not exist

10,327

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

Share:
10,327
tprieboj
Author by

tprieboj

Updated on June 08, 2022

Comments

  • tprieboj
    tprieboj almost 2 years

    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)
    
    • Reinard
      Reinard over 8 years
      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.
    • fge
      fge over 8 years
      If you use Java 7+ you should consider using java.nio.file instead
    • user207421
      user207421 over 8 years
      Why? What good is an empty file to you? And an empty String? Just catch FileNotFoundException, or better still let it be thrown.