有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用“文件”读取而不修改实际文件?

我有以下代码:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Printer {
    private File f;
    private Scanner in;

    public Printer(){
        try {
            f = new File("C:\\Users\\Bob\\Desktop\\num.txt");
            in = new Scanner(f);
        }catch (IOException i){
            System.out.println(i.getMessage());
        }
    }

    public double average(){
        int count = 0;
        double total = 0;
        while (in.hasNext()){
            count++;
            total += in.nextInt();
        }
        return total / count;
    }

    public void readFile(){
        while (in.hasNext()){
            System.out.println(in.next());
        }
    }
}

主要内容:

public class Main {
    public static void main(String[] args) {
        Printer mine = new Printer();
        System.out.println(mine.average());
        mine.readFile();
    }
}

输出:

5.666666666666667 注:我还希望打印出每个单词

如何在不修改文件的情况下读取文件?我注意到,如果我执行in.nextInt();,它将从文件中删除该值。此外,当我调试并且我的编译器到达while (in.hasNext()){时,它直接跳过了循环。如果有人能告诉我一种在不修改文件的情况下读取文件的方法,我将不胜感激。我需要在我的一个硬件任务中使用它,该任务声明假定该文件将只使用一次,但是我想让它更“动态”,因此能够保留该文件及其原始内容以供以后使用


共 (2) 个答案

  1. # 1 楼答案

    您可以通过以下方式读取文件:

        try {
            BufferedReader br = new BufferedReader(new FileReader(pathToFile));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
    
            while (line != null) {
    
                line = br.readLine();
            }
    
        }catch(Exception e){
            System.out.println(e);
            System.out.println("Error");
        }
    
  2. # 2 楼答案

    How can I read from a file without modifying it? I noticed that if I do in.nextInt(); it removes the value from the file.

    您没有修改该文件。您正在更改扫描仪在文件中指向的位置

    while (in.hasNext()){ it jumped right over the loop.

    这意味着在线上没有更多的单词。hasNext()检查有问题的行中是否还有其他单词

    读取文件不会改变它,因此您所做的已经是正确的想法

    一旦您读取了该文件,它就不知道您想再次启动该文件。您可以从一开始就重新打开该文件,但是

    您的硬件似乎建议您将数据保存在List<Integer>中,以便在需要时稍后打印