Search code examples
javaarraysarraylistfileoutputstreambufferedwriter

How to write different values to multiple output files in Java?


I have the following Java 8 code that creates 1 file fine (the content in the file is a singular line of text). What's the best way to change this code so I end up with three separate text files?

String os = System.getProperty("os.name");
String jv = System.getProperty("java.version");
String userfolder = System.getProperty("user.home");

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(userfolder + "opsys.txt"), "utf-8")))
                {
                 writer.write((String) os);
                } catch (UnsupportedEncodingException e) 
                {
                e.printStackTrace();
                } catch (FileNotFoundException e) 
                {
                e.printStackTrace();
                } catch (IOException e) 
                {
                e.printStackTrace();
                }

Output I'm trying to achieve:

  • 3 text files
    • named opsys.txt, version.txt and userhome.txt.
    • Each file contains the relevant System.getProperty answer.

Solution

  • you can put all the functionality for write files in a separate method, something like:

    private void writeFile(String fileName, String content) {
    
        try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(fileName), "utf-8")))
        {
            writer.write((String) content);
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    

    After that, your previous code becomes something like:

    String os = System.getProperty("os.name");
    String jv = System.getProperty("java.version");
    String userfolder = System.getProperty("user.home");
    
    //Here you call the writeFile method the number of time that you need:
    writeFile(userfolder + "opsys.txt", os);
    ....
    

    With this approach you can create any files that you need.