从java中的文件中读取数据

我有一个以下格式的文本文件:

Details.txt

该文件是.txt文件。 我想从这个文件中读取课程标题并打印相应的教科书和讲师信息。 但我不确定要遵循什么流程? 将信息存储在数组中效率不高! 我该怎么办? 注意:我无法更改文件中的信息,不应更改!! 很明显,该文件将由以下代码读取:

File newFile=new File("C:/details"); 

但是我应该如何根据标签课程标题,教科书和讲师从这个文件中提取数据!?

  1. 首先逐行正确读取文件,并搜索您输入的课程标题,让我们考虑“Java”

  2. 现在你点击你的标题,你知道你需要从你的文件连续3行,因为所有与该标题相关的信息都在那里。

     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. 现在在这四行上进行字符串操作并根据需要提取数据并使用它。

我在家,所以我无法给你准确的代码。 但如果你遵循这个,它将解决你的问题。 如果您在执行此操作时遇到任何问题,请告诉我。

按照此操作获取有关String操作的一些信息

使用String Tokenizer并分隔每个字符串,然后将它们存储在链接列表或数组列表中。 每个标题都有单独的列表,如课程标题,讲师等,然后打印出来

 //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); 

你可以使用FileUtils.readFileToString(new File(“”C:/details.txt“);

现在,您可以根据自己的意愿提取所需的数据

使用Scanner类

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

如果你想逐字工作,那么使用String Tokenizer

看到这篇文章