有 Java 编程相关的问题?

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

JAVA:通过按键将文本文件前进到下一行

我正在用Java编写一个程序,在按下一个键(很可能是ENTER键)后,它将逐行推进文本。我有一个文本扫描器,它可以扫描整个文本文件。如何编写一个按键事件,使文本文件前进到下一行

这是文本扫描仪:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class textReader {



public static void main(String[] args) {
    
    try
    {
        FileInputStream fis = new FileInputStream("ftp.txt");
        Scanner sc = new Scanner(fis);
        
        while(sc.hasNextLine()) {
            System.out.println(sc.nextLine());
        }
        sc.close();
        }
    catch(IOException e) {
        e.printStackTrace();
    }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    通过在while循环中添加一行,您可以非常简单地等待“回车”键:

    while(sc.hasNextLine()) {
        System.out.println(sc.nextLine());
        System.in.read()
    }
    
  2. # 2 楼答案

    编辑解决方案:


    那么:

         public static void main(String[] args) {
            Scanner awaitEnter = new Scanner(System.in);
            try {
                FileInputStream fileInputStream = new FileInputStream("ftp.txt");
                Scanner scanner = new Scanner(fileInputStream);
    
                while(scanner.hasNextLine()) {
                    System.out.print(scanner.nextLine());
                    awaitEnter.nextLine();// blocks until user hits enter
                }
                scanner.close();
    
            } catch(IOException e) {
                throw new RuntimeException("Check file exists???");
            }
            awaitEnter.close();
        }