【问题标题】:Copying text line for line, using Scanner and FileWriter, Not appending使用 Scanner 和 FileWriter 逐行复制文本,不附加
【发布时间】:2015-10-23 20:09:41
【问题描述】:

在这里不知所措。一直在玩弄这个试图弄清楚如何复制单个字符串,逐行复制并将其附加到副本中。如果副本存在则删除,如果不存在则创建,我可以看到控制台中出现的每一行文本,但它不会附加到新副本中。

import java.io.*;
import java.util.Scanner;

public class FriendListCopy
{
    public static void main(String[] args) throws IOException
{
    String str;
    File file = new File("FriendList.txt");
    Scanner inputFile = new Scanner(file);
    File newFile = new File("FriendListCopy.txt");
    FileWriter fw = new FileWriter("FriendListCopy.txt", true);
    PrintWriter pw = new PrintWriter(fw);
    if(file.exists()) 
    {
        if(newFile.exists())
            newFile.delete();
        if(!newFile.exists())
            newFile.createNewFile();
        while(inputFile.hasNext())
        {
            str = inputFile.nextLine();
            pw.println(str);
            System.out.println(str);
        }
    }
    else
    {
        inputFile.close();
        pw.close();
        System.exit(1);
    }
    inputFile.close();
    pw.close();
    fw.close();
    }
}

忽略所有关闭语句,我只是在试验。 我有一种感觉,这个方法不能用,但也许我只是忽略了一些东西。感谢您提供任何帮助。 使用Linux,如果有帮助的话。权限:

-rw-r--r-- 1  users 1724 Oct 23 11:51 FriendList.class
-rw-r--r-- 1  users 1197 Oct 23 15:52 FriendListCopy.class
-rw-r--r-- 1  users  761 Oct 23 15:49 FriendListCopy.java
-rw-r--r-- 1  users    0 Oct 23 15:51 FriendListCopy.txt
-rw-r--r-- 1  users 1124 Oct 23 11:37 FriendList.java
-rw-r--r-- 1  users   46 Oct 23 11:27 FriendList.txt

【问题讨论】:

  • 好吧,"但它不会附加到新副本中" 对我来说很好。第二次运行程序后,副本不包含两次“FriendList.txt”的内容?
  • 不应该删除一个副本(如果存在),然后创建一个新副本。我的副本文件没有一行
  • "不,如果存在就删除一个副本,然后创建一个新的。" 嗯,很明显这行不通,因为你已经打开了该文件用于写入,那么您的程序应该如何删除它?这个 “我的副本文件没有一行” 是不同的。 ...但同样,它对我来说效果很好。
  • 我认为,只要文件存在,while循环中的调用就应该起作用。
  • 如果它适用于其他所有人,我想这是权限问题。

标签: java file java.util.scanner filewriter printwriter


【解决方案1】:

摆脱所有文件存在/删除/创建废话。 new FileWriter() 已经完成了这一切。即使您以正确的顺序完成了它,您仍然会复制所有内容。

如果您是初学者,请不要用 NIO 让您的生活复杂化。

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 2020-04-11
    • 1970-01-01
    • 2018-06-18
    • 2011-08-02
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多