【问题标题】:Java code for modifying txt file contents will not function properly用于修改 txt 文件内容的 Java 代码将无法正常运行
【发布时间】:2020-11-10 15:29:05
【问题描述】:

我对 java 很陌生,正在做一个基本的项目,正在试验 txt 文件。 在这种情况下,我有一个名为“活动”的 txt 文件,其中包含一组活动,每个活动都与一个 ID 相关联。然后用户可以通过以下代码决定是否查看、添加或修改活动:

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


public class ActivitiesModification {
    private static Scanner x;
    public static void main(String[] args) throws IOException {
    
        String acfilepath = "C:\\Users\\John\\Desktop\\Activities.txt";
        
        File actxt = new File(acfilepath); //Name of the File Storing the activities (currently on desktop)
        
        FileWriter fw = new FileWriter(actxt, true);                      //FileWriter object representing the Activities txt file
        
        PrintWriter pw = new PrintWriter(fw);                             //PrintWriter object representing the Activities txt file
        
        Scanner sc = new Scanner(actxt);                                  //Scanner object which will scan through the txt file
        
        Scanner scinput = new Scanner(System.in);                         //Scanner object which scans user input
        
        System.out.println("What would you like to do? (view/add/modify)");
        
        String action = scinput.nextLine();                               //User input responsible for switch statement (Pre-UI temporary)
        
        switch(action) {
            case("view"):{
                System.out.println("The currently available activities are as follows:");
                viewActivities(actxt);
                break;
        }
            case("add"):{
                System.out.println("Please add the desired activity name");
                String addac = scinput.nextLine();
                int counter = 1;
                while(sc.hasNextLine()){
                    sc.nextLine();
                    counter++;
                }
                
                pw.println(counter + " " + addac);
                break;
        }
            case("modify"):{
            System.out.println("Please enter the ID of the activity whose name you would like to modify");
            
            String editTerm = scinput.nextLine();
            
            System.out.println("Please enter the new activity name");
            
            String newActivity = scinput.nextLine();
            
            editActivities(acfilepath, editTerm, newActivity);
            
            System.out.println("The activity name has been changed as requested. Would you like to view the full list of available activities?");
            
            String ds = scinput.nextLine();
            
            if(ds.equalsIgnoreCase("yes")) {
                
                viewActivities(actxt);
            }
        
        }
    }
    pw.close(); 
    scinput.close();
    sc.close(); 
    }


    
    public static void editActivities(String filepath, String editTerm, String newActivity) {
        String tempFile = "C:\\Users\\John\\Desktop\\temp.txt";
        File oldFile = new File(filepath);
        File newFile = new File(tempFile);
        String ID = ""; String activity = "";
        try {
            FileWriter fw1 = new FileWriter(tempFile, true);
            BufferedWriter bw1 = new BufferedWriter(fw1);
            PrintWriter pw1 = new PrintWriter(bw1);
            x = new Scanner(new File(filepath));
            
            while(x.hasNext()) {
                ID = x.next();
                activity = x.next();
                if(ID.equals(editTerm)) {
                    pw1.println(ID + " " + newActivity);
                }
                    else {
                        pw1.println(ID + " " + activity);
                    }

            }
            x.close();
            pw1.flush();
            pw1.close();
            bw1.close();
            fw1.close();
            oldFile.delete();
            File dump = new File(filepath);
            newFile.renameTo(dump);
        }
        catch(Exception e) {
            
        }
    }
    
    public static void viewActivities(File filepath) throws FileNotFoundException { // "filepath" will be the name of the file object which the scanner will scan through (actxt)
        Scanner sc = new Scanner(filepath);
        while(sc.hasNextLine()) {
            System.out.println(sc.nextLine());
        }
        sc.close();
    }
    
    
    }

但是,由于某种原因,代码的“修改”部分将无法正常运行。无需创建新的临时文件,删除旧文件并重命名临时文件活动。它只是创建一个临时文件,传输适当的内容,而不是删除/重命名。

我最初在另一个项目上运行了上述代码(使用相同的文件),它运行良好。将代码转移到此项目中的方法时,它停止工作,我不知道为什么。

【问题讨论】:

  • catch(Exception e) {} 这不能很好地结束......不要忽略异常。至少在那里打印一个堆栈跟踪。
  • 所以我添加了一个布尔变量来显示重命名和删除过程是否发生。正如我所想,他们没有。但我无法确定原因。
  • 我不确定你在说什么布尔值。正如我所说,在catch(如e.printStackTrace();)中打印堆栈跟踪。可能发生的情况是 editActivities 方法中的某些内容正在破坏,而您只是忽略了它。通过打印堆栈跟踪,您将知道什么是中断以及为什么。
  • 我做了,没有打印出来。通过一些简单的调试,代码运行没有错误,但由于某种原因它忽略了重命名和删除部分。

标签: java text findandmodify


【解决方案1】:

在 Windows 上,您无法删除(或重命名)当前打开的文件。

如果我正确阅读了您的代码:

  • 您的editActivities 方法正在用于“编辑”文件“C:\Users\John\Desktop\Activities.txt”,

  • 在您调用editActivities 时,您已经为该文件打开了FileWriter/

这可能是删除和重命名没有发生的原因。


正如 Federico 指出的那样,捕获和压缩异常是有问题的。它会丢弃错误证据。

还有:

  • 您应该检查File.delete 和File.renameTo 调用的结果。或者更好的是,重写代码以使用Files 和Path 而不是File。

  • 您似乎同时打开了一个文件进行读写:

    FileWriter fw = new FileWriter(actxt, true);
    PrintWriter pw = new PrintWriter(fw);   
    Scanner sc = new Scanner(actxt);    // <<< === WHAT???
    
  • 您不需要在关闭 Writer 之前刷新它。 close() 将刷新所有未写入的数据。

  • 您不需要同时关闭 FileWriter 和包裹它的 BufferedWriter 以及包裹它的 PrintWriter。只需关闭PrintWriter

  • 您似乎正在创建 File 对象而不是使用它们。

  • 您应该更多地关注您的代码实际在做什么。目前看起来很混乱。你做了一些事情,然后几行之后再次做同样的事情......好像你忘记了你以前做过。

  • 我不明白您为什么将 x 声明为静态字段。它应该是一个局部变量,因为它只用于一种方法。

  • 您应该更加注意正确缩进。

【讨论】:

  • 感谢您的详细回复。我根据建议更改了代码,更改了扫描仪,并关闭了必要的 PrintWriter,但代码仍然拒绝删除/重命名文件。我很困惑,因为它可以在文件相同的单独项目上运行得很好。
  • “或者更好的是,重写代码以使用文件和路径而不是文件。” - 当删除或重命名失败时,这将引发异常并提供信息性消息。跨度>
猜你喜欢
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
相关资源
最近更新 更多