我的扫描仪有问题。如果我把扫描器传递到一个静态方法中,扫描器就不能读取在主函数中给出的文件。当我将文件对象传递到scanner,然后将scanner传递到add函数时,它不会将文件内容输出到控制台。但是,如果我将添加功能的扫描器部分注释掉,扫描器的读数将很好。这让我相信扫描器可以看到文件,但不能从中读取。我的问题是,我应该如何再次从文件中读取数据,这次是在添加函数中?
public static void main(String[] args) throws IOException { File file = new File("vinceandphil.txt"); if (file.createNewFile()) { System.out.println("New file was created"); } else { System.out.println("File already exists"); } Scanner sc = new Scanner(file); FileWriter writer = new FileWriter(file); writer.write("Test data\n"); Add(file, writer, sc); writer.close(); while (sc.hasNextLine()) { System.out.println(sc.nextLine()); } sc.close(); } public static void Add(File f, FileWriter w, Scanner scanner) throws IOException { if (f.exists()) { w.write("Got em coach\n"); w.write("We need more info\n"); w.write("Come again\n"); } while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } }
你不能那样做。一旦一行通过 nextLine() 它被“丢弃”,指针指向下一个。
nextLine()
要从文件的开头重新开始,必须实例化另一个 Scanner .
Scanner
final Scanner yourNewScanner = new Scanner(file);
如果您想在文件中移动,请查看 RandomAccessFile .
RandomAccessFile
你在指出你的 扫描仪 不打印任何内容。 这是因为在询问 扫描仪 阅读。
扫描仪
if (f.exists()) { w.write("Got em coach\n"); w.write("We need more info\n"); w.write("Come again\n"); // Adding this call flushes and closes the data stream. w.close(); }