繁体   English   中英

如何将数据从数组写入文本文件?

[英]How to write data from an array into a text file?

我正在编写一个简单的程序,询问用户姓名,姓氏和年龄,然后将其保存到文本文件中,但是先前的数据将被删除。 我已经在阅读文本文件并可以显示它,但是无法将其写入文本文件。

这是我正在使用的代码:

import java.util.Scanner;
import java.io.*;
public class UserData{
public static void main (String args[]) throws IOException{
    //Initialisations
    Scanner scan = new 
    Scanner(System.in);
    File UserData = new File(PATH OF FILE);
    BufferedWriter b = new BufferedWriter(new FileWriter(UserData));


    //Reader for Writer Old Data
    String text[] = new String[10];
    int count = 0;
    String path = PATH OF FILE;
    BufferedReader reader = new BufferedReader(new FileReader(path));
    String line = null;
    while ((line = reader.readLine()) != null){
        text[count] = line;
        count++;
    }

    PrintWriter pr = new PrintWriter(PATH OF FILE);    
    for (int I=0; I<text.length ; I++)
    {
        pr.println(text);
    }



    //Writer
    System.out.println("Enter your name");
    String name = scan.nextLine();
    pr.println(name);
    b.newLine();
    System.out.println("Enter your surname");
    String surname = scan.nextLine();
    pr.println(surname);
    b.newLine();
    System.out.println("Enter your age");
    int age = scan.nextInt();
    pr.println(String.valueOf(age));
    pr.close();
}

}

FileWriter类具有构造函数

public FileWriter(File file,
          boolean append)
           throws IOException

给定File对象,构造一个FileWriter对象。

在您的代码中-将第9行更改为

BufferedWriter b = new BufferedWriter(new FileWriter(UserData),true);

如果第二个参数为true,则字节将被写入文件的末尾而不是开头。

这是规范: 类FileWriter构造函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM