简体   繁体   English

有没有办法修改文件并从具有新内容的新文件中读取?

[英]Is there a way to modify a file and read from the new file, which has the new content?

When I delete a line from a text file, add it to a temporary text file, then replace the temporary file with the original, the scanner isn't loading the correct text. 当我从文本文件中删除一行时,将其添加到临时文本文件,然后用原始文件替换临时文件,扫描仪没有加载正确的文本。 It is loading the content from the original file, not the updated file. 它正在加载原始文件中的内容,而不是更新的文件。 I want it to load the updated file with the new content. 我希望它用新内容加载更新的文件。

try
{
    File inputFile = new File("department.txt");
    File tempFile = new File("departmentTemp.txt");

    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

    String lineToRemove = departResIDField.getText();
    String currentLine;

    while((currentLine = reader.readLine()) != null) 
    {
         String trimmedLine = currentLine.trim();
         if(trimmedLine.startsWith(lineToRemove)) continue;
         writer.write(currentLine + System.getProperty("line.separator"));
    }

    writer.close(); 
    reader.close(); 
    inputFile.delete();
    tempFile.renameTo(inputFile);

    fWriter = new FileWriter(inputFile.getAbsoluteFile(), true);
    printOut = new PrintWriter(fWriter);
    writer = new BufferedWriter(fWriter);
    writer.write(departResIDField.getText() + "\t" + 
    departResNameField.getText() + "\r\n");
    writer.close();

    int result = Integer.parseInt(departResIDField.getText());
    depart.add(new Department(result, departResNameField.getText()));

    insResDepartModel.addElement(departResNameField.getText());

    depart.remove();

    //This is where I am having problem with the code
    //The scanner is scanning old data not the updated data             
    Scanner scan = new Scanner(inputFile);

    while(scan.hasNext())
    {
        depart.add(new Department(scan.nextInt(), scan.next()));
    }
    scan.close();

    for(int i = 0; i < depart.getSize(); i++)
    {
        Department d1 = depart.get(i);
        System.out.println(d1.departID + d1.departName);
    }

    menuLayout.show(cardLayout, "15");
    departResIDField.setText(null);
    departResNameField.setText(null);
    departUpdateButton.setVisible(false);
    departCancelButton.setVisible(false);
} catch (IOException f) 
    {
        f.printStackTrace();
    }

Output: 1 Biology 2 Chemistry 4 Statistics 5 Physics 3 Math 输出:1生物学2化学4统计学5物理3数学

Expected Output: 1 Biology 2 Chemistry 4 Statistics 5 Physics 3 Calculus 预期产出:1生物学2化学4统计5物理3微积分

Code removes "3 Math" and adds "3 Calculus 代码删除“3 Math”并添加“3微积分

Of course there is a way. 当然有办法。 But I would recommend you to save with something like a LinkedList , on an text file if you want only save subjects, and try to read and write only one File . 但是,如果您只想保存主题,我会建议您在文本文件中保存类似LinkedList的内容,并尝试只读取和写入一个File You can save complex data structures with ObjectOutputStream for example. 例如,您可以使用ObjectOutputStream保存复杂的数据结构。 LinkedList java utility has an instruction named replace to modify certain index. LinkedList java实用程序有一个名为replace的指令来修改某个索引。 So if you want to modify the File you load the LinkedList saved then you modify the list and save it in the same file. 因此,如果要修改File ,则加载已保存的LinkedList然后修改列表并将其保存在同一文件中。

From my understanding, you want to replace the line containing "3 Math" with "3 Calculus". 根据我的理解,您希望将包含“3 Math”的行替换为“3 Calculus”。 If that's the case you can do something like this: 如果是这种情况,你可以这样做:

    Path wiki_path = Paths.get("data/sample.txt");
    Charset charset = Charset.forName("UTF-8");

    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      List<String> lines = Files.readAllLines(wiki_path, charset);
      int targetToReplaceIndex = -1;

      // You can modify this part to match your logic
      for (int i = 0; i < lines.size(); i++) {
          if (lines.get(i).startsWith("3 Math")) {
              targetToReplaceIndex = i;
              break;
          }
      }
      lines.set(targetToReplaceIndex, "3 Calculus");

      File temp = File.createTempFile("temp", ".tmp");
      temp.deleteOnExit();

      BufferedWriter out = new BufferedWriter(new FileWriter(temp));

      out.write(convertListToContent(lines));
      out.close();

      File orig = new File("data/sample.txt");

      fis = new FileInputStream(temp);
      fos = new FileOutputStream(orig);

      FileChannel src = fis.getChannel();
      FileChannel dest = fos.getChannel();
      dest.transferFrom(src, 0, src.size());

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
        try {
            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

The method to convert a list of Strings into a single String is pretty straight forward using Java 8: 使用Java 8将字符串列表转换为单个String方法非常简单:

private static String convertListToContent(List<String> lines) {
    StringBuilder contentBuilder = new StringBuilder();

    lines.forEach(l -> contentBuilder.append(l).append("\n"));

    return contentBuilder.toString();
}

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 读取,扫描,修改文本文件并将修改后的文本放入新文件 - Read, scan, modify a text file and put modified text into a new file 有没有一种方法可以将类从文件实现为新文件? - Is there a way to implement classes from a file into a new file? 如何打开和读取文件并将特定内容写入新文件? - How to open and read a file and write specific content to a new file? 读取黄瓜中的 .feature 文件并将内容复制到新的特征文件中 - Read .feature file in cucumber and copy content to new feature file 使用从文件读入的新数据更新JTextArea - Updating JTextArea with new data read in from file 读取文件,替换字符串并创建一个包含所有内容的新文件 - Read file, replace string and create a new one with all content 如何从响应中读取 pdf 的内容并将其写入另一个新的 pdf 文件 - How to read the pdf content from response and write it to another new pdf file 读取 POST 请求正文 PDF 内容并创建新的 PDF 文件 - Read POST request body PDF content and create new PDF File 从另一个具有太多工作表的excel创建一个新的工作表excel文件 - Creating a new one sheet excel file from another excel which has too many sheets 将新条目添加到具有dup键的json文件中 - Add new entry to the json file which has dup key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM