2012-12-15 23 views
0

讀取數據我有以下格式的文本文件:從文件在java中

Details.txt

該文件是一個文本文件。我想從這個文件中讀取課程標題並打印相應的教科書和教師信息。但我不確定要遵循什麼流程?將信息存儲在數組中將不會有效!我應該如何繼續?注:我不能更改文件中的信息,它不應該改變!顯然該文件將通過下面的代碼讀取:

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

但我應該如何從該文件根據標籤課程名稱,教材和教師提取數據!?

+0

它是電子表格文件嗎? –

+0

可以請你分享你的文本文件格式?使用哪個分隔符? –

+0

不,它是一個.txt文檔 – Chandeep

回答

0
  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. 現在這些四行做字符串操作,並根據您的需要,並用它提取您的數據。

我在家所以我不能給你確切的代碼。但如果你遵循這一點,它將解決你的問題。如果您在執行此操作時遇到任何問題,請告知我們。

Follow this to get some info on String operations

0

使用字符串標記器並分隔每個字符串,然後將它們存儲在鏈接列表或數組列表中。有單獨的列表像課程名稱,講師等每一個標題,然後打印出來

+2

現在不鼓勵使用string tokenizer .. split()可能是一個選項.. – Chandeep

0

使用掃描儀類

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

,如果你在工作想要的字,然後用字符串標記

看到這個article

+2

正確你的代碼'while(s.hasNext())' –

0
//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

可以使用FileUtils.readFileToString(新文件( 「」 C:/details.txt「);

現在,你可以根據你的願望