当前位置: 首页 > 知识库问答 >
问题:

为什么这只是复制txt文件中的最后一行?

年风华
2023-03-14

我正在处理此代码的特定部分,该部分允许用户更改有关保存在txt文件中的项目的详细信息。每个项目都保存在单独的行上,如下所示:

1, Project House Tyson, Building Type: House, Project Address: 365 Long Ave, ERF Number: 12jk, Total Fee Charged: 1000, Amount Paid to Date: 900, Project Deadline: 01 October 2021, Project Contractor: Bob, Lead Architect: Ted, Client: Mike Tyson, Complete: No

如果用户输入“c”,将要求他们在菜单中键入项目名称,然后输入“a”更改日期。这一切都很好,除了不只是更改txt文件中所需行的日期,而是用文件中最后一行的副本替换项目。

它最终看起来像这样(注意第3行的项目现在是第5行的副本,但是有了新的日期):

1, Project House Tyson, Building Type: House, Project Address: 365 Long Ave, ERF Number: 12jk, Total Fee Charged: 1000, Amount Paid to Date: 900, Project Deadline: 01 October 2021, Project Contractor: Bob, Lead Architect: Ted, Client: Mike Tyson, Complete: No
2, Project House Jordan, Building Type: house, Project Address: 75 Elgin Rd, ERF Number: mj23, Total Fee Charged: 1000, Amount Paid to Date: 900, 11 October 2021, Project Contractor: Bob, Lead Architect: Ted, Client: Mike Jordan, Complete: No
5, Project test3, Building Type: house, Project Address: 3i, ERF Number: 2k2k, Total Fee Charged: 10101, Amount Paid to Date: 2020, 05 October 2021, Project Contractor: ten, Lead Architect: dido, Client: kokolk, Complete: No
4, Project test2, Building Type: hh, Project Address: jhj, ERF Number: hjh, Total Fee Charged: hjh, Amount Paid to Date: hjh, Project Deadline: hjh, Project Contractor: hjh, Lead Architect: hjh, Client: hjh, Complete: No
5, Project test3, Building Type: house, Project Address: 3i, ERF Number: 2k2k, Total Fee Charged: 10101, Amount Paid to Date: 2020, Project Deadline: 01 December 2021, Project Contractor: ten, Lead Architect: dido, Client: kokolk, Complete: No

这是用户与菜单交互的主要方法。我觉得问题不在这里,只是供一些参考:

public class MenuV4 extends ExceptionHandling {

public static void main (String args[]) throws IOException, ParseException {
    
    //File object to store project info
    try {
        File file = new File("C:\\CurrentProjects.txt");
        
    }catch (Exception e){
        System.out.println("Error at main");
    }
    
    //Options at main menu displayed to user
    while (true) {
        System.out.println("\nPlease choose a number option from the menu below: "
                + "\na) View Projects"
                + "\nb) Add Project"
                + "\nc) Edit Project"
                + "\nd) Finalize a Project"
                + "\ne) View Incomplete Projects"
                + "\nf) View Overdue Projects"
                + "\ng) Exit program");
    
    //Checking user input is valid with string check method from Exception Handling class
    //fileCheck boolean makes sure that there is at least one project in the file object
    String userChoice = stringCheck("menu choice"); 
    boolean projects = fileCheck();
    
    if ((projects == true) && (userChoice.equals("a") || userChoice.equals("A"))) {  
        Projects object = new Projects();
        object.viewProjects();
        
    
    } else if (userChoice.equals("b") || userChoice.equals("B")) {  
        CreateProject setNew = new CreateProject();
        setNew.CreateProject();
        
    //Here is where the problem is, user enters 'c' to edit a project 
    } else if ((projects == true) && (userChoice.equals("c") || userChoice.equals("C"))) {  
        
        //User is prompted to enter the number of the project they would like to edit
        //This input is put through stringCheck
        //User can choose to change due date or fees paid
        System.out.println("Please enter the name of the project you wish to update: \n");
        String projectInfo = stringCheck("project number");
        System.out.println("Would you like to:" + 
                "\na) Edit the project due date or" +
                "\nb} Edit the total amount paid of the fee to date?");
        
        //Again put through stingCheck
        String editChoice = stringCheck("edit choice");
        Projects obj1 = new Projects();
        int lineCount = obj1.loadProjects(projectInfo);
        obj1.updateProject(editChoice, lineCount);  

找到他们正在寻找的项目的方法如下所示:

public class Projects extends ExceptionHandling{

public int loadProjects(String projectInfo) {
    String[] info = new String[12];  
    int lineCount = 1;  
    
    // A new file object is created and a while loop used to run through lines in the test file.
    // Line info is then split and stored in the array.
    // While loop is exited if the second index in the array matches projectInfo parameter (typed in by user)
    try {
        File file = new File("C:\\CurrentProjects.txt");  
        Scanner projectFile = new Scanner(file);
        
        while (projectFile.hasNextLine()) {  
            
            info = projectFile.nextLine().split(", "); 
            
            if ((info[1].equalsIgnoreCase("Project " + projectInfo)) || (info[1].equalsIgnoreCase(projectInfo))) {
                break;  
                
            } else {
                lineCount++; 
                
            }
        }
    } catch (FileNotFoundException e) {  
        System.out.println("Error.");

    }
    return lineCount;  
}

更改项目截止日期的方法看起来像这样,也在Projects类中:我认为问题出在这个方法的某个地方。

public void updateProject (String editChoice, int lineCount) {
    
    ArrayList<String> infoArray = new ArrayList<String>();
    String[] info = new String[12];
    int findLine = 1;
    
    // A file object is created and a while loop used to run through each line of the text file.
    // Each line of project information is added to the ArrayList.
    try {
        File file = new File("C:\\CurrentProjects.txt");
        Scanner projectFile = new Scanner(file);
        
        while (projectFile.hasNextLine()) {
            infoArray.add(projectFile.nextLine());  
    
        }
    
    } catch (FileNotFoundException e) {  
        System.out.println("Error51");
    }
    
    //Create another file object.
    // Each line of the text file is run through and when the lineCount matches the findLine variable, then the line info is split.
    // That specific split line info is then stored in the info string array.
    try {
        File file = new File("C:\\CurrentProjects.txt");
        Scanner projectFile = new Scanner(file);
        
        while (projectFile.hasNextLine()) {
            if (findLine == lineCount) {
                info = projectFile.nextLine().split(", ");
                System.out.println(Arrays.toString(info));
                
            } else if (findLine != lineCount) {  // Line count incremented if match is not made.
                findLine++;
            }
        }
    
    } catch (FileNotFoundException e) {
        System.out.println("Error.");
    }
    
     //If the user chose edit choice 'a', they are prompted for a new due date.
     //The new due date info is then inserted into index number 7 in the info array
     //The info array is then converted into a string, with extra characters removed ("[]")
     //The finalised string 'newLine' is then inserted into the correct index of the infoArray ArrayList (i.e. lineCount -1).
     //The same process is followed for edit choice 'b', except they are prompted for a new total amount, which is replaced at index 6 in the info array.
    if (editChoice.equals("a") || editChoice.equals("A")) {
        System.out.println("Please enter a new project due date: ");
        String newDeadline = stringCheck("due date");
        info[7] = newDeadline;
        String newInfo = Arrays.toString(info);
        String changeLine = newInfo.replace("[", "");
        String newLine = changeLine.replace("]", "");
        infoArray.set(lineCount-1, newLine);
        
    } else if (editChoice.equals("b") || editChoice.equals("B")) {
        System.out.println("Please enter a new total amount of the fee paid to date:");
        String newAmount = stringCheck("new total amount");
        info[6] = newAmount;
        String newInfo = Arrays.toString(info);
        String changeLine = newInfo.replace("[", "");
        String newLine = changeLine.replace("]", "");
        infoArray.set(lineCount-1, newLine);
        
    }
    
    
    //Re-write to the CurrentProjects.txt file.
    try {
        Formatter F = new Formatter("C:\\CurrentProjects.txt");
        for (String element : infoArray) {
            F.format("%s", element + "\r\n");
        }
        System.out.println("Project successfully updated.");  
        F.close();
        
    } catch (Exception e) {
        System.out.println("Error.");  
        
    }   
}

共有1个答案

皇甫浩壤
2023-03-14

我过去一直在编辑txt文件,我也遇到过这个问题。

我认为问题在于它正在访问以前版本的信息数组列表,在你的情况下,infoArray。

所以为了解决这个问题,我有一个方法可以从infoArray中删除所有数据,这样就无法从以前版本的txt文件中访问任何信息。这是一种方法:

public void removeInfo(ArrayList<String> info) {
    while(info.size() > 0) {
        info.remove(0);
    }
}

我不完全确定这个remove方法应该在你的代码中的什么位置,但是我希望它有所帮助。

 类似资料:
  • 我有兴趣写一个批处理脚本,它将在一个有许多其他文本块的. txt文件中复制最后一个文本块。想想执行脚本的日志文件,但没有任何一致的内容或长度。每个条目由空行分隔。 因此,对于以下文件,我只想选择并复制最后一段: 知识是一种美德,是一种美德,是一种美德,是一种美德。 但是,在最低限度上,我们需要一个实验室来进行日常工作。 杜伊斯奥特鲁尔杜洛在谴责在波罗的海韦尔特埃塞西莱姆杜洛雷欧盟逃犯nulla p

  • 我有一个方法,它接受源地址、目标地址和,然后它通过giver source文件夹,用ArrayList项检查每个文件,如果它们有相同的名称,那么它就用完全相同的文件夹结构复制目标(因此它需要文件夹)。在这里之前一切都有效。但如果ArrayList的项是文件夹名,则会出现错误。有些怎么找不到那个文件夹,然后出现错误。 在我的另一个mathchine中,我得到了同样的错误,但它是而不是。 所以任何让它

  • 我创建了一个复制类,它接受源文件夹和目标文件夹以及一个文件名数组。因此,该类搜索源文件夹,如果遇到与数组元素同名的文件,则将该文件复制到与源文件夹结构相同的文件夹结构中。下面是课程: 指向这一行:`新的复制文件(src、dest、array); 有什么解决的办法吗?

  • 我正在尝试使用日志将txt文件加载到弹性搜索中。txt 文件是一个简单的文本,由 3 行组成,如下所示: 文本文件 我的conf文件如下所示: 运行这个并转到Kibana后,我可以看到正在创建的索引。但是,我看到的唯一消息是前两行,最后一行没有显示。这是我看到的: 基巴纳页面 有人知道为什么最后一行没有被导入,我该如何解决这个问题吗? 谢谢大家的帮助。

  • 创建一个同步多线程系统,以确定三个文本文件中所有整数或分数的总数。如果流被阻塞,则必须将其名称显示为"LOCKED"。为什么只计算一个文件(带锁的线程)?程序显示的内容:Thread-0 Locked!线程-2锁定!123.321 322099只有一个文件

  • 问题内容: 我正在尝试将名为 City 的 类的 对象添加到中。这是该类的代码 __ 这是我的 主班 的代码 __ 的结果始终相同,并且似乎 数组列表 仅存储添加到其所有元素中的最后一个对象。 例如,运行程序时得到的结果是: 为什么我得到那个结果?我该如何解决? 提前致谢! 问题答案: 在和变量被标记为。甲构件跨过的所有实例共享,并且因此是一个全局变量。您需要对代码进行几处更改: 将city中的和