read data from a file in java

后端 未结 5 1146
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 04:32

I have a text file in the following format:

Details.txt

The file is a .txt file. I want to read course title from this file and print corresponding textbook

相关标签:
5条回答
  • 2021-01-17 05:16

    Use Scanner class

    Scanner s=new Scanner(new File("C:/Details.txt"));
    while(s.hasNext())
    {
      System.out.println(s.nextLine());
    }
    

    if you want in work by word then use String Tokenizer

    see this article

    0 讨论(0)
  • 2021-01-17 05:17

    Use String Tokenizer and separate each string and then store them in a Linked List or Array List. Have Separate List for each title like course title, instructor etc. and then print them

    0 讨论(0)
  • 2021-01-17 05:23
    //Find the directory for the SD Card using the API
    //*Don't* hardcode "/sdcard"
    File sdcard = Environment.getExternalStorageDirectory();
    
    //Get the text file
    File file = new File(sdcard,"file.txt");
    
    //Read text from file
    StringBuilder text = new StringBuilder();
    
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
    
        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
    }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }
    
    //Find the view by its id
    TextView tv = (TextView)findViewById(R.id.text_view);
    
    //Set the text
    tv.setText(text);
    
    0 讨论(0)
  • 2021-01-17 05:26

    you can use FileUtils.readFileToString(new File(""C:/details.txt");

    Now you can extract the required data based on your wish

    0 讨论(0)
  • 2021-01-17 05:30
    1. First read the file correctly line by line, and search for your entered course title, lets consider "Java"

    2. Now you hit your title and you know you need 3 consecutive lines from your file as all information related to that title are there.

      if(str.startsWith(title)); {  // for title = "Java"
        line1 = 1st line  // contains ISBN and First Name
        line2 = 2nd line  // Title and Last Name
        line3 = 3rd line  // Author and Department
        line4 = 4th line  // Email
        break;  // this will take you out of while loop
      }
      
    3. Now on those four lines do string operations and extract your data as you need and use it.

    I am home so I can't give you exact code. But if you follow this it will solve your issue. Let me know if any problem you got while doing this.

    Follow this to get some info on String operations

    0 讨论(0)
提交回复
热议问题