0

我对 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();
    }
    
    
    }

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

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

4

1 回答 1

0

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

我正在正确阅读您的代码:

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

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

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


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

还:

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

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

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

  • 您不需要同时关闭包装它的 AND 和FileWriter包装它的 。只需关闭BufferedWriterPrintWriterPrintWriter

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

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

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

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

于 2020-07-21T10:03:11.133 回答