0

I have the method like below to read the file:

String[] readFile(String file) throws IOException {
    String[] contentFile;

    BufferedReader br = new BufferedReader(new FileReader(path + file + ".txt"));

    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (true) {
            sb.append(line);
           // sb.append(System.lineSeparator());
            line = br.readLine();
            if (line == null) {
                break;
            }
....

But when the file in FileReader does not - exists there is an exception. How to create the file before initializang BufferedReader if it does not exists in the above case?

Dawid
  • 53
  • 9
  • 1
    Probably a duplicate of https://stackoverflow.com/questions/9620683/java-fileoutputstream-create-file-if-not-exists – Dennis Hunziker Apr 28 '18 at 19:02
  • So you want to create an empty file if the file doesn't exist? Maybe better just handle the exception? – Bogdan Lukiyanchuk Apr 28 '18 at 19:06
  • Maybe use of this constructor will work `public FileReader(FileDescriptor fd)`: https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html#FileReader-java.io.FileDescriptor- – scrutari Apr 28 '18 at 19:09
  • 1
    But what do you want to read as the file does not exist ? Do you want to return empty string or null from the function ? – krokodilko Apr 28 '18 at 19:16
  • When the program starts - it reads the file and creates the objects from the Strings in the file. Then the file may be overwritten. But when I start the program for the first time the file does not exists so I would like to create it. – Dawid Apr 28 '18 at 19:22

1 Answers1

0

The sollution:

File f = new File(path + fileName + ".txt");
    if (!f.exists()){
        f.createNewFile();
    }
Dawid
  • 53
  • 9