Reading and displaying data from a .txt file

后端 未结 10 945
北海茫月
北海茫月 2020-11-27 15:41

How do you read and display data from .txt files?

10条回答
  •  北海茫月
    2020-11-27 15:51

    Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).

    import java.io.*;
    import java.util.Scanner;
    import java.io.*;
    
    public class TestRead
    {
    public static void main(String[] input)
    {
        String fname;
        Scanner scan = new Scanner(System.in);
    
        /* enter filename with extension to open and read its content */
    
        System.out.print("Enter File Name to Open (with extension like file.txt) : ");
        fname = scan.nextLine();
    
        /* this will reference only one line at a time */
    
        String line = null;
        try
        {
            /* FileReader reads text files in the default encoding */
            FileReader fileReader = new FileReader(fname);
    
            /* always wrap the FileReader in BufferedReader */
            BufferedReader bufferedReader = new BufferedReader(fileReader);
    
            while((line = bufferedReader.readLine()) != null)
            {
                System.out.println(line);
            }
    
            /* always close the file after use */
            bufferedReader.close();
        }
        catch(IOException ex)
        {
            System.out.println("Error reading file named '" + fname + "'");
        }
    }
    

    }

提交回复
热议问题