【问题标题】:Reading this file rather than creating a new one?阅读这个文件而不是创建一个新文件?
【发布时间】:2013-09-12 11:00:07
【问题描述】:

所以现在我正在为一款名为 Minecraft 的游戏制作“朋友”系统。问题是当你重新启动时,你没有朋友!无论如何,它都会创建一个新文件,而不是读取前一个文件。这是我的代码:

public static boolean friends = true;
public static List friend = new ArrayList();


public static void friendsList(){
    if(friends){
        try{
            File file = new File("friends.txt");
            BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(file));
            for(int i = 0; i < friend.size(); i++){
                bufferedwriter.write((new StringBuilder()).append((String) friend.get(i)).append("\r\n").toString());
            }
            bufferedwriter.close();
        }
        catch(Exception exception){
            System.err.print(exception.toString());
        }
    }
}

我不知道这是否很重要,但这是你添加朋友的方法(par1Str是你发送聊天消息时输入的字符串):

if(par1Str.startsWith("&friendadd")){
        Camb.friends = true;
        String as0[] = par1Str.split(" ");
        Camb.friend.add(as0[1]);
        mc.thePlayer.addChatMessage("\2479[CAMB]\247e Added Friend.");
        Camb.friendsList();
        Camb.friends = false;
        return;
    }

如果文件已经存在,我将如何做到这一点,它将从中加载而不是覆盖它?

谢谢

【问题讨论】:

  • 我没有看到任何读取好友文件的代码。
  • 检查文件是否存在,并读入?
  • 首先致电file.exists()。另外:你的write() 调用很时髦,你知道你不需要StringBuilder,只需调用bufferedWriter.write((String) friends.get(i)); bufferedWriter.write("\r\n");。或者+ 两者结合在一起——关于将Strings 与+ 连接起来的性能警告主要是废话——你可能永远不会写出区别很重要的程序。
  • 另外,如果您出于某种原因不需要在记事本中查看文件,则不需要 "\r\n"。 “\n”就足够了。

标签: java arrays string file


【解决方案1】:

您有时需要阅读包含好友列表的文件。然后您可以设置一个标志以避免再次将其写出。

【讨论】:

    【解决方案2】:

    检查文件是否已经存在非常容易。

    File f = new File("friends.txt");
    
    if(f.exists()){
        System.out.println("File exists"); 
        //Append to the end
    } else{
        System.out.println("File not found!");
    }
    

    【讨论】:

    • 嗯...我有点困惑。我将如何在我的代码中实际实现这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2021-08-28
    • 2020-10-26
    相关资源
    最近更新 更多