【问题标题】:Reading specific lines of a text file in Java在 Java 中读取文本文件的特定行
【发布时间】:2015-12-23 09:05:15
【问题描述】:

我是 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 行就有一个新条目。例如,Salary 是类别,3,400 是金额,21/12/2015 是日期。我想做的是只读取金额(例如 3,400 3 320 1,230 等)。我唯一成功做的就是通过在真正的打印语句上匹配它们来打印行,使用以下代码:

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.

【问题讨论】:

标签: java java.util.scanner file-handling file-read


【解决方案1】:

跳过其他行 :-)

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

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

    // skip date
    opnEsoda.nextLine();

    System.out.println(); 
} 

【讨论】:

    【解决方案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)
    

    【讨论】:

    • 谢谢。那行得通。接下来我要做的是将这些数字相加,记录每个金额的日期并打印周、月和年的统计数据。
    • 您可以使用 Integer.parseInt( ) 将 String 值转换为整数值。剩下的应该很容易使用一些合适的数学运算符。
    • @AlexAndreadis 见that question
    【解决方案3】:

    您可以使用下面的 JAVA8 代码并以字符串列表的格式获取文件。 检索列表的行号“n”将很容易。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      相关资源
      最近更新 更多