我可以用一种方法读取和写入不同的 txt 文件吗(我正在读取的文件中的内容被删除)?

Can i read and write on different txt files in a method (contents in the file that im reading gets deleted)?

我想创建一个方法来读取特定的 .txt 文件,与另一个已分配给数组的特定 .txt 文件进行比较,然后如果它们不匹配,则编写一个打印问题的 .txt。是否可以在读取另一个 .txt 文件的同时写入一个 .txt 文件? (注意:我使用 PrintWriter 写入文件,使用 Scanner 读取文件)

public static void updateInventory(String filename1, String filename2, String[] name1, int[] quantity1) {
  File updated = new File(filename1);
  Scanner input = new Scanner(updated);
  File log = new File(filename2);
  PrintWriter output = new PrintWriter(log);

  int i = 0;

  while(input.hasNext()) {
     do {
        String s = input.next();
        s = s.substring(0,1).toUpperCase() + s.substring(1).toLowerCase();
        if (s == name1[i]) {
           int num = input.nextInt();
           if (num >= 0 && num < quantity1[i]) {
              quantity1[i] -= num ;
           }               
        }
        i++;
     } while(i < name1.length);

     if (i == name1.length) {
        output.println("ERROR: Item " + s + " not found");
     }

     if (num < 0) {
        output.println("ERROR: Invalid amount requested (" + num + ")");
     }

     input.close();
     output.close();
  }    
}

您的代码需要进行以下改进:

  1. 使用FileWriter(File file, boolean append)以附加模式打开日志文件。
  2. 使用 string1.equals(string2) 而不是 string1==string2 来比较 string1string2
  3. 在使用nextInt()之前使用hasNextInt()
  4. 使用 while 循环的终止条件考虑所有方面,例如可能使它无限地 运行 的值和 while 循环内的代码正在使用的值。

完整代码如下:

public static void updateInventory(String filename1, String filename2, String[] name1, int[] quantity1) {
    File updated = new File(filename1);
    Scanner input = null;
    try {
        input = new Scanner(updated);
    } catch (FileNotFoundException e) {
        System.out.println("Error reading file, " + filename1);
    }
    FileWriter log = null;
    PrintWriter output = null;
    try {
        log = new FileWriter(filename2, true);
        output = new PrintWriter(log);
    } catch (Exception e) {
        System.out.println("Error creating log file, " + filename2);
    }
    int i = 0;
    int num = 0;
    String s;
    while (input != null && input.hasNext() && i < name1.length && i < quantity1.length) {
        s = input.next();
        s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
        if (s.equals(name1[i]) && input.hasNextInt()) {
            num = input.nextInt();
            if (num >= 0 && num < quantity1[i]) {
                quantity1[i] -= num;
            }
        }
        if (i == name1.length) {
            output.println("ERROR: Item " + s + " not found");
        }
        if (num < 0) {
            output.println("ERROR: Invalid amount requested (" + num + ")");
        }
        i++;
    }
    output.close();
    input.close();
}

我已经使用一些虚拟值测试了这段代码。如果您在使用过程中遇到任何问题,请随时发表评论。