Home > Net >  How to set a File variable name as a string
How to set a File variable name as a string

Time:10-01

So I'm trying to make a method that uses a few parameters to quickly and easily create and write to a file. I'm trying to set the File variable name (the thing that would be in the parenthesis of a writer method) to be the same as the file name as it's listed in the directory.

Sample code:

        
        File fileName = new File(directory   "//"   fileName   ".txt"); //this line gives me a duplicate local variable error
        try {
            FileWriter writer1 = new FileWriter(fileName   ".txt");
            writer1.write(input);
            writer1.close();
        } catch(IOException e) {
            System.out.println("Error: Problem writing to file");
        }
    }

Any help is appreciated : )

CodePudding user response:

So I'm trying to make a method that uses a few parameters to quickly and easily create and write to a file.

You're badly reinventing the wheel. Java already has this.

Files.write(Paths.get("/path/to/myfile.txt", "Hello, World!");

(Files and Paths is from the java.nio.file package).

This has many, many advantages:

  • No need to reinvent the wheel and in so doing, make code that is needlessly unfamiliar to others.
  • That one gives proper error messages.
  • That one properly thinks about charset encoding.
  • That one doesn't have a resource leak problem.

CodePudding user response:

A careful look at the line will reveal you already have a variable named fileName that you are using there. Use a different name. Also, prefer a try-with-Resources over an explicit close() (and if you're going to use an explicit close() you should have a finally block). Please don't silently swallow exceptions, at least display what the error was. Like,

File fileName2 = new File(directory, fileName   ".txt");
try (FileWriter writer1 = new FileWriter(fileName2)) {
    writer1.write(input);
} catch (IOException e) {
    System.out.println("Error: Problem writing to file "   e.getMessage());
}
  • Related