【问题标题】:How to write in a text file in java without deleting the content of the file before如何在java中写入文本文件而不删除之前的文件内容
【发布时间】:2017-12-16 10:28:19
【问题描述】:

这是删除文件内容然后在其上写入的代码 我想在文件中写入而不删除内容并写在最后一行

import java.io.*;
import java.util.Scanner;

public class SetValues {

    public void setNumberPhone(String numberPhone) throws UnsupportedEncodingException {
        Scanner input = new Scanner(System.in);
        PrintWriter pr = null;

        try {
            input = new Scanner("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt");
            pr = new PrintWriter("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt", "UTF-8");

        } catch (FileNotFoundException e) {
            System.out.println("Not Open" + e.getMessage());
            System.exit(0);
        }

        if (input.hasNext()) {
            pr.println(numberPhone);
        }
        pr.close();

    }
}

【问题讨论】:

标签: java file text filewriter printwriter


【解决方案1】:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;

OutputStream os = Files.newOutputStream(Paths.get("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt"), APPEND);
PrintWriter pr = new PrintWriter(os);

pr.println("TEXT");

这将创建一个输出流,其中任何输出文本都将附加到文件的当前内容中。您可以使用 OutputStream 创建一个 PrintWriter。更多信息可以找到at the Java documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 2016-03-07
    相关资源
    最近更新 更多