簡體   English   中英

從Java中的文件讀取數據

[英]read data from a file in java

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

Details.txt

該文件是.txt文件。 我想從該文件中讀取課程標題,並打印相應的教科書和教師信息。 但是我不確定該遵循什么程序? 將信息存儲在數組中效率不高! 我應該如何進行? 注意:我無法更改文件中的信息,因此不應更改! 顯然,該文件將通過以下代碼讀取:

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

但是我應該如何根據標簽的課程名稱,課本和講師從該文件中提取數據!

使用String Tokenizer並分隔每個字符串,然后將它們存儲在Linked List或Array List中。 為每個標題(如課程標題,講師等)設置單獨的列表,然后打印它們

使用掃描儀類

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

如果您想按單詞工作,則使用字符串標記器

看這篇文章

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

現在,您可以根據自己的意願提取所需的數據

  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. 現在,在這四行上執行字符串操作,並根據需要提取並使用數據。

我在家,所以我不能給你確切的代碼。 但是,如果您遵循此步驟,則可以解決您的問題。 讓我知道您在執行此操作時是否遇到任何問題。

按照此操作獲取有關字符串操作的一些信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM