简体   繁体   中英

Trying to read a txt file in Java

I'm supposed to be reading and displaying a simple text file to the screen for the user, and I can't seem to figure it out. Any help appreciated, thank you.

import java.io.*;
import static java.lang.System.in;
import java.util.Scanner;

public class PersonReader 
{
    public static void main(String[] args) throws FileNotFoundException, IOException 
    {
        Scanner reader = new Scanner(System.in);
        String textFile = SafeInput.getString(reader, "What file would you like to read?: ");
        try(BufferedReader br = new BufferedReader(new FileReader(textFile + ".txt")))
        {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) 
            {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            String everything = sb.toString();
        }
    }
}

You did not print your final stringbuilder string.

import java.io.*;
import java.util.Scanner;

public class PersonReader {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner reader = new Scanner(System.in);
        System.out.println("What file would you like to read?: ");
        String textFile = reader.nextLine();

        File f = new File(textFile + ".txt");
        if (f.isFile()) {
            Scanner sc = new Scanner(f);
            StringBuilder sb = new StringBuilder();
            while (sc.hasNextLine()) {
                sb.append(sc.nextLine() + System.lineSeparator());
            }
            System.out.println(sb);
            sc.close();
        }
        else {
            System.out.println("could not find file: " + textFile + ".txt");
        }
        reader.close();
    }
}

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