Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 706
tprieboj Avatar asked Oct 14 '25 15:10

tprieboj


2 Answers

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

like image 54
Bon Avatar answered Oct 17 '25 04:10

Bon


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.

like image 26
Shoham Avatar answered Oct 17 '25 06:10

Shoham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!