使用ArrayList写入文本文件

时间:2012-07-11 19:12:11

标签: java

该程序基本上是从文本文件中读取,将当前数据存储到ArrayList中,然后将数据(从用户输入)写入同一文本文件。请告诉我这个子部分出错的地方?文本文件中的数据如下:

  

abc t1 1900

     

xyz t2 1700

编译器在行output.format("%s%s%s%n",

处显示错误
public class justTesting {
    private Scanner input;
    private Formatter output;
    private ArrayList<Student> tk = new ArrayList<Student>();

    public static void main(String[] args) {
        justTesting app = new justTesting();

        app.create();
        app.writeToFile();
    }

    public void create() {
        Text entry = new Text();
        Scanner input = new Scanner(System.in);

        System.out.printf("%s\n", "Please enter your name, ID, and year: ");

        while (input.hasNext()) {
            try {
                entry.setName(input.next());
                entry.setTelNumber(input.next());
                entry.setDOB(input.next());

                for (int i = 0; i < tk.size(); i++) {
                    output.format("%s%s%s%n", tk.get(i).getName(), tk.get(i)
                            .getTelNumber(), tk.get(i).getDOB());
                }

            } catch (FormatterClosedException fce) {
                System.err.println("Error writing to file.");
                return;
            } catch (NoSuchElementException nsee) {
                System.err.println("Invalid input. Try again: ");
                input.nextLine();
            }
            System.out.printf("%s\n", "Please enter your name, ID, and year: ");
        }
    }

    public void writeToFile() {
        try {
            output = new Formatter("testing.txt");
        } catch (SecurityException se) {
            System.err
                    .println("You do not have write access permission to this file.");
            System.exit(1);
        } catch (FileNotFoundException fnfe) {
            System.err.println("Error opening or creating file.");
            System.exit(1);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我删除了%n并且它有效。谢谢大家。