如何在Java中为多个输出文件写入不同的值?

时间:2017-04-24 19:45:36

标签: java arrays arraylist fileoutputstream bufferedwriter

我有以下Java 8代码可以创建1个文件(文件中的内容是单行文本)。更改此代码的最佳方法是什么,以便最终得到三个单独的文本文件?

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();
                }

输出我正在努力实现:

  • 3个文本文件
    • 命名为opsys.txt,version.txt和userhome.txt。
    • 每个文件都包含相关的System.getProperty答案。

2 个答案:

答案 0 :(得分:0)

您可以将写入文件的所有功能放在一个单独的方法中,例如:

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();
    }
}

之后,您之前的代码变为:

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);
....

使用此方法,您可以创建所需的任何文件。

答案 1 :(得分:0)

您可以创建一个简单的方法,如下所示,它将fileName和环境变量名称作为输入参数:

public void createAndWriteFile(String fileNmae, String envName) {
        String content = System.getProperty(envName);
        String userfolder = System.getProperty("user.home");
        try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(userfolder + fileNmae), "utf-8"))) {
         writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }

现在,调用上述方法3次,如下所示:

String os = System.getProperty("os.name");
createAndWriteFile("opsys.txt",os);
String javaVersion = System.getProperty("java.version");
createAndWriteFile("version.txt",javaVersion);
String userHome = System.getProperty("user.home");
createAndWriteFile("userhome.txt",userHome);