如何在java中向File添加内容

问题描述 投票:0回答:1
public static void main(String args[]) {
        decode E = new decode();
        String input = "apple";
       encode output  = E.compute(input);
        System.out.println("input decoded :" +E.d_decode(output))
}

嗨,我希望将输出打印在文件中,而不是将其打印到控制台。我怎么做?我希望在运行时创建文件。我的意思是我没有将输出添加到已创建的文件中

请耐心等待,因为我是java的新手

java arrays arraylist
1个回答
1
投票

您可以使用Java 7中提供的java.nio.file.Files在运行时将内容写入文件。如果您提供正确的路径,也将创建该文件,您也可以设置首选编码。

JAVA 7+

在@Ivan的建议之后编辑

你可以使用PrintWriterBufferedWriterFileUtils等。有很多方法。我和Files分享了一个例子

String encodedString = "some higly secret text";
Path filePath = Paths.get("file.txt");
try {
    Files.write(filePath, encodedString, Charset.forName("UTF-8"));
} catch (IOException e) {
    e.printStackTrace();
    System.out.println("unable to write to file, reason"+e.getMessage());
}

写多行

List<String> linesToWrite = new ArrayList<>();
linesToWrite.add("encodedString 1");
linesToWrite.add("encodedString 2");
linesToWrite.add("encodedString 3");
Path filePath = Paths.get("file.txt");
try {
    Files.write(filePath, linesToWrite, Charset.forName("UTF-8"));
} catch (IOException e) {
    e.printStackTrace();
    System.out.println("unable to write to file, reason"+e.getMessage());
}

还有一百万种其他方式,但我认为因为它的简单性而开始是好的。

在Java 7之前

PrintWriter writer = null;
String encodedString = "some higly secret 
try {
    writer = new PrintWriter("file.txt", "UTF-8");
    writer.println(encodedString);
    // to write multiple: writer.println("new line")
} catch (FileNotFoundException | UnsupportedEncodingException e) {
    e.printStackTrace();
}  finally {
    writer.close();
}
© www.soinside.com 2019 - 2024. All rights reserved.