读取文本文件并从文本文件中打印特定文本

时间:2018-12-05 17:03:28

标签: java.util.scanner inputstream bufferedreader filereader

我的程序需要读取文本文件,但要求用户输入1到4之间的整数以从文本中打印出特定的日期 到目前为止,我的代码使用FileReader和BufferedReader

import java.util.Scanner;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TestingTwo {

    public static void main(String[] input)

    {
        String fileName;
        Scanner keyboard = new Scanner(System.in);

        /*Enter the text file name with extension to open and read its content*/

        System.out.println("Enter file name you want to open");
        fileName = keyboard.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(fileName);

            //Always wrap up 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(FileNotFoundException e)
        {
            System.out.println("File could not be found");
        }
        catch(IOException e)
        {
            System.out.println("Error reading file named " + fileName);
        }
    }
}

我的代码的主要问题是它显示了整个文本文件,但是我只想要用户想要的特定日期。

0 个答案:

没有答案