2015-12-23 64 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; 
     }