#file IO

1 messages · Page 1 of 1 (latest)

warm blade
#

Hi i need some help, I am given a file path and need to open said file and write to it, if it doesnt exist I need to create and then write to it. How do I do this?

silver irisBOT
#

<@&987246399047479336> please have a look, thanks.

silver irisBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

silver lily
warm blade
#

of opening a file and creating a file

#

to me they both seem to be

#

File x = new File(filePath);

silver lily
#

There may not even be a file at that path. That's why File has an exists() method

#

To create a file at that path, you'd call create()

pseudo cedar
#

I wonder if there's a way to improve this code.

#
        //I am given a file path and need to open said file and write to it, if it doesnt exist I need to create and then write to it. How do I do this?
        try{
            deleteFile("test.txt", "test2.txt");
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }


    private static void solution(String file) throws Exception{
        File t  = new File(file);
        if (t.exists()){
            //do logic
            writeToFile(t);
        }else{
            t.createNewFile();
            writeToFile(t);
        }
    }
    private static void writeToFile(File f) throws Exception{
        FileWriter fr = new FileWriter(f);
        BufferedWriter bw = new BufferedWriter(fr);
        String str = "Hello my name is ilyase and I love to eat pancakes";
        bw.write(str);
        bw.close();
        fr.close();
    }

    private static void deleteFile(String... f){
        for (String str : f){
            File file = new File(str);
            if (file.exists()){
                file.delete();
                System.out.println("deleted the file here !");
            }
            else{
                System.out.println("this file is not here !");
            }
        }
    }
silver irisBOT
# pseudo cedar ``` public static void main(String[] args){ //I am given a file path ...

Detected code, here are some useful tools:

Formatted code
public static void main(String[] args) {
  //I am given a file path and need to open said file and write to it, if it doesnt exist I need to create and then write to it. How do I do this?
  try {
    deleteFile("test.txt", "test2.txt");
  } catch (Exception e) {
    e.printStackTrace();
  }
}
private static void solution(String file) throws Exception {
  File t = new File(file);
  if (t.exists()) {
    //do logic
    writeToFile(t);
  }
  else {
    t.createNewFile();
    writeToFile(t);
  }
}
private static void writeToFile(File f) throws Exception {
  FileWriter fr = new FileWriter(f);
  BufferedWriter bw = new BufferedWriter(fr);
  String str = "Hello my name is ilyase and I love to eat pancakes";
  bw.write(str);
  bw.close();
  fr.close();
}
private static void deleteFile(String...f) {
  for (String str : f) {
    File file = new File(str);
    if (file.exists()) {
      file.delete();
      System.out.println("deleted the file here !");
    }
    else {
      System.out.println("this file is not here !");
    }
  }
}
silver lily
silver irisBOT
#

File IO in Java should be done preferably with NIO (Java 7+), revolving around the classes Files and Path; and not with the old interface File, BufferedReader, FileReader and similar.

NIO is simple to use. The path to a file is represented using the Path class:

Path path = Path.of("myFile.txt");

All file operations can be found in the Files class:

// Reading
List<String> allLines = Files.readAllLines(path);
// or as a single string
String content = Files.readString(path);
// or with a stream
try (Stream<String> stream = Files.lines(path)) {
  stream.forEach(System.out::println);
}

// Writing
Files.write(path, lines);
// or as a single string
Files.writeString(path, "hello world");
// or with extra options
Files.writeString(path, "hello world",
  StandardOpenOption.WRITE,
  StandardOpenOption.CREATE,
  StandardOpenOption.APPEND);

If you need more control over the process, you can fallback to the old interface, but prefer using the bridge methods from NIO (Files.newBufferedReader, Files.newInputStream, path.toFile() and similar) to benefit from advantages such as correct encoding and better error detection.

Here is a simple example of how to read a file line-wise with the old interface

try (BufferedReader br = Files.newBufferedReader(path)) {
  String line;
  while ((line = br.readLine()) != null) {
    System.out.println(line);
  }
}

it is way more verbose than NIO but it gives more control.

You must not forget to close file handles, even in all exceptional cases. Closing a handle manually is very hard, which is why you should always use try-with-resources for this to let Java automatically close the handle for you:

try (SomeResource resource = ...) {
  ...
} // Automatically closed here, even in exceptional cases
silver lily
#

You could use br.lines().toList() instead of "the old way". Doesn't use NIO

#

Although NIO is definitely the way to go

silver lily
#

New IO