ArrayList 和 BufferedReader 笔记程序
Posted
技术标签:
【中文标题】ArrayList 和 BufferedReader 笔记程序【英文标题】:ArrayList and BufferedReader Note Taking Program 【发布时间】:2015-10-01 16:20:18 【问题描述】:我创建了一个简单的程序,它采用标题和您输入的注释,然后您可以选择使用 BufferedWriter
将注释导出到 txt 文件,但是因为每个注释都是存储在 ArrayList
中的对象当存储它们时,我遍历一个增强循环,当我遍历所有对象时,它会不断复制每个音符。
笔记类
import java.util.*;
public class Notes
private String notes;
private String titleOfNotes;
Scanner input = new Scanner(System.in);
public Notes()
titleOfNote(input);
takeNotes(input);
public void takeNotes(Scanner x)
System.out.println("Please Enter Your Note");
notes = x.nextLine();
public void titleOfNote(Scanner y)
System.out.println("Please Enter Title");
titleOfNotes = y.nextLine();
public String toString()
return "Title: " + titleOfNotes + "\t" + notes;
App Class //完成大部分工作
import java.util.*;
import java.io.*;
public class App
private int exit = 0;
private int createANote;
private int displayTheNotes;
private int inputFromUser;
public boolean haveFileBeenWritten = true;
File file = new File("Notes.txt");
Scanner input = new Scanner(System.in);
ArrayList<Notes> arrayOfNotes = new ArrayList<Notes>();
public void makeNoteObject()
arrayOfNotes.add(new Notes());
public void displayAllTheNote(ArrayList<Notes> n)
for(Notes singleObjectOfNote : n)
System.out.println(singleObjectOfNote);
public void programUI()
while(exit != 1)
System.out.println("1. Create A Note");
System.out.println("2. Display The Notes");
System.out.println("3. Exit");
System.out.println("4. Export to text file");
System.out.println("Enter Your Operation");
inputFromUser = input.nextInt();
if(inputFromUser == 1)
makeNoteObject();
else if(inputFromUser == 2)
displayAllTheNote(arrayOfNotes);
else if(inputFromUser == 3)
System.out.println("Exited");
exit = 1;
else if(inputFromUser == 4)
makeATxtFileFromNotes(arrayOfNotes);
System.out.println("Textfile created filename: " + file.toString());
else
System.out.println("You Select A Invalid Command");
public void makeATxtFileFromNotes(ArrayList<Notes> x)
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
//Problem here!
for(Notes singleObjectOfNotes : x)
bw.write(singleObjectOfNotes.toString());
bw.newLine();
catch(IOException e)
System.out.println("Cant Write File: " + file.toString());
haveFileBeenWritten = false;
public App()
programUI();
public static void main(String[]args)
App objectOfApp = new App();
我是 Java 新手,所以我的代码不是最好的!
【问题讨论】:
【参考方案1】:如果您的问题是只需要查看当前列表的Notes
不包括上一个',那是因为这行:
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
默认情况下,haveFileBeenWritten
是 true
,因此基于 FileWriter API,它将在现有文件 Notes.txt
上追加,所以如果您不希望这样,请将其更改为 @ 987654328@.
参数:
file - 要写入的 File 对象
append - 如果为真,那么字节将是 写入文件末尾而不是开头
编辑:要访问List<>
元素,请使用get()
。
例子:
int size = myList.size();
for (int i = 0 ; i < size ; i++)
//...
Notes note = myList.get(i);
//...
【讨论】:
以上是关于ArrayList 和 BufferedReader 笔记程序的主要内容,如果未能解决你的问题,请参考以下文章