2015-12-23 66 views
1

我是Java新手。我試圖在文本文件上做一個數據庫(不要問我爲什麼)。事情是我想要做的是讀取文本文件的特定行。閱讀Java中的文本文件的特定行

文本文件:

Salary 
3,400 
21/12/2015 
Tax Refund 
3 
22/12/2015 
Tax Refund 
320 
23/12/2015 
Savings Deposit 
1,230 
23/12/2015 
Bonus 
343 
23/12/2015 

每3行有一個新的條目。例如,薪水是類別,3,400是數量,21/12/2015是日期。我想要做的只是讀取數量(例如3,400 3 320 1,230等)。我成功做的唯一的事情是在真正的print語句匹配他們打印的線條,與此代碼:

while(opnEsoda.hasNext()) { // diabazei kathe seira sto txt 
    // diabazei kathe seira kai emfanizei to value tis kathe mias ana 3. 
    System.out.print("You got money from: " + opnEsoda.nextLine()+ ", "); 

    System.out.print("Amount: " + opnEsoda.nextLine()+", "); 
    System.out.print("Date: " + opnEsoda.nextLine()+". ");    
    System.out.println(); 
} 

opnEsoda掃描器和打印:

You got money from: Salary, Amount: 3,400, Date: 21/12/2015. 
You got money from: Tax Refund, Amount: 3, Date: 22/12/2015. 
You got money from: Tax Refund, Amount: 320, Date: 23/12/2015. 
You got money from: Savings Deposit, Amount: 1,230, Date: 23/12/2015. 
You got money from: Bonus, Amount: 343, Date: 23/12/2015. 
+0

什麼問題,有機會獲得跳過的元素呢? – sidgate

+0

@sidgate我需要做什麼,只打印金額? (例如3,400,3 320 1,230等)。 –

+0

可能的重複:https://stackoverflow.com/questions/16201045/java-reading-nth-line –

回答

2

這在我看來是不是僅僅跳過線清潔了一下,它可以讓你櫃面你需要他們後來:)

do 
{ 
    String[] entry = new String[3]; 

    for (int i = 0; i < 3; i++) 
    { 
     if (opnEsoda.hasNextLine()) 
     { 
      // Trim removes leading or trailing whitespace. 
      entry[i] = opnEsoda.nextLine().trim(); 
     } 
    } 

    System.out.println(entry[2]); 
} 
while (opnEsoda.hasNextLine) 
+0

謝謝。這工作。接下來我想要做的就是總結這些數字,計算每個數量的日期並打印周,月和年的統計數據。 –

+0

您可以使用Integer.parseInt()將字符串值轉換爲整數值。其餘的應該很容易,一些好的數學運算符。 – Hatefiend

+0

@AlexAndreadis看到[那個問題](http://stackoverflow.com/questions/999172/how-to-parse-a-date) – cadrian

2

只是跳過其他行:-)

while(opnEsoda.hasNext()) { 
    // skip category 
    opnEsoda.nextLine(); 

    System.out.print("Amount: " + opnEsoda.nextLine()+", "); 

    // skip date 
    opnEsoda.nextLine(); 

    System.out.println(); 
} 
2

您可以使用下面的JAVA8代碼,並以String列表的格式獲取文件。 很容易檢索列表中的行號'n'。

 int n=2; 
     List<String> fileLines = Files.readAllLines(Paths.get("c:\\abc.txt")); 
     while(n<fileLines.size()){ 
      fileLines.get(n); 
      n+=3; 
     }