简体   繁体   English

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

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

I am writing a simple program which asks the user for his name, surname and age and then saves it to a text file, however the previous data gets deleted. 我正在编写一个简单的程序,询问用户姓名,姓氏和年龄,然后将其保存到文本文件中,但是先前的数据将被删除。 I am already reading the text file and can display it but I cant write it to the text file. 我已经在阅读文本文件并可以显示它,但是无法将其写入文本文件。

This is the code I am using: 这是我正在使用的代码:

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 class has a constructor FileWriter类具有构造函数

public FileWriter(File file,
          boolean append)
           throws IOException

Constructs a FileWriter object given a File object. 给定File对象,构造一个FileWriter对象。

In Your code - Change line no 9 to 在您的代码中-将第9行更改为

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

If the second argument is true, then bytes will be written to the end of the file rather than the beginning. 如果第二个参数为true,则字节将被写入文件的末尾而不是开头。

Here is the specification: Class FileWriter Constructors 这是规范: 类FileWriter构造函数

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

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