Home > Software engineering >  How to safely combine strings into file path and open filewriter?
How to safely combine strings into file path and open filewriter?

Time:05-08

Is there a more elegant way to do the following?

try (FileWriter myWriter = new FileWriter(Paths.get(folder,fileName).toAbsolutePath().toString())){

I have folder path and filename as string and I want to safely combine them. For example if

String folder = "/tmp/"
String fileName = "/myfile.txt"

to not end up with

"/tmp//myfile.txt"

or with

String folder = "/tmp"
String fileName = "myfile.txt"

to not end up with

"/tmpmyfile.txt"

The way I am using is transforming String to path and back to String which feels weird, but it looks like FileWriter does not accept Path directly.

Is there some more elegant solution than the one I have?

CodePudding user response:

Use Files.newBufferedWriter(Path, OpenOption...).

try (Writer myWriter = Files.newBufferedWriter(Paths.get(folder, fileName))) {
    // other code
}

Note that, while the FileWriter constructor uses the JVM's default encoding, this method uses the UTF-8 encoding, which is considered generally more useful. If you need to replicate the behavior of the FileWriter constructor, use

Files.newBufferedWriter(path, Charset.defaultCharset());
  • Related