使用字符串更新.txt文件

时间:2013-11-27 08:34:56

标签: java file-io arraylist java.util.scanner printwriter

我正在尝试编写一个使用新String更新.txt文件的方法.....我所做的就是拥有它1)从之前制作的txt文件中读取所有字符串 2)将他们变成一个arraylist 3)将新字符串写入arraylist 4)然后将该arraylist的toString()对象写入新文件

它只会将最新的字符串写入文件,即使我用多行编辑文件也不会写其他文件

这就是我所拥有的:

public static void updateNames(String newName) throws FileNotFoundException {
        name = new File("names.txt");
        infile = new Scanner(name);
        ArrayList<String> nameslist = new ArrayList<>();
        while(infile.hasNext()) {
            nameslist.add(infile.nextLine());
        }
        infile.close();
        nameslist.add(newName);
        names = new PrintWriter("names.txt");
        for(int i=0;i<nameslist.size();i++) {
            names.println(nameslist.get(i).toString());
        }
        names.close();
        System.out.println("else");
    }

只是要尽可能明确{name,names,infile}在类的开头都被声明为静态void

提前感谢任何帮助

2 个答案:

答案 0 :(得分:0)

为什么不尝试这个:

public static void updateNames(String newName) throws FileNotFoundException   {
    try {
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
        out.println(newName);
        out.close();
    } catch (IOException e) {
}

它会在文件文本的末尾添加newName

答案 1 :(得分:0)

使用infile.hasNextLine()代替infile.hasNext()

更改

   while(infile.hasNext())

  while(infile.hasNextLine())

和小修正

更改

 names.println(nameslist.get(i).toString());

 names.println(nameslist.get(i)); //nameslist holds String objects no need to convert to String again.

如果没有解决问题,请添加countline变量并确保从文件中读取了多少行。

 int countline;
 while(infile.hasNext()) {
     nameslist.add(infile.nextLine());
     countline++;        
 }     
 System.out.println("Number of line: "+ countline);
相关问题