简体   繁体   中英

Read a single line from text file & not the entire file (using buffered reader)

I am trying to write a piece of code that reads a single line of text from a text file in java using a buffered reader. For example, the code would output the single line from the text file and then you would type what it says and then it would output the next line and so on.

My code so far:

public class JavaApplication6 {

    public static String scannedrap;
    public static String scannedrapper;

    public static void main(String[] args) throws FileNotFoundException, IOException {
        File Tunes;
        Tunes = new File("E:\\NEA/90sTunes.txt");

        System.out.println("Ready? Y/N");
        Scanner SnD;
        SnD = new Scanner(System.in);
        String QnA = SnD.nextLine();

        if (QnA.equals("y") || QnA.equals("Y")) {

            System.out.println("ok, starting game...\n");
            try {

                File f = new File("E:\\NEA/90sTunes.txt");

                BufferedReader b = new BufferedReader(new FileReader(f));

                String readLine = "";

                while ((readLine = b.readLine()) != null) {
                    System.out.println(readLine);
                }

            } catch (IOException e) {
            }
        }
    }
}

It outputs:

Ready? Y/N
y
ok, starting game...
(and then the whole text file)

But I wish to achieve something like this:

Ready? Y/N 
y
ok, starting game...
(first line of file outputted)
please enter (the line outputted)

& then repeat this, going through every line in the text file until it reaches the end of the text file (where it would output something like "game complete")...

This block of code reads the whole file line by line, without stopping to ask for user input:

        while ((readLine = b.readLine()) != null) {
            System.out.println(readLine);
        }

Consider adding a statement to the loop body that seeks some input from the user, like you did above when asking if they were ready ( you only need to add one line of code to the loop, like the line that assigns a value to QnA )

这将读取第一行“.get(0)”。

String line0 = Files.readAllLines(Paths.get("enter_file_name.txt")).get(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM