JAVA:从文件中读取nextLine,排除所有空格

时间:2017-12-04 15:36:31

标签: java arrays whitespace filereader readline

我目前难以理解如何在删除所有空格的同时从文本文件中读取内容。我已经尝试使用分隔符和字符串拆分找不到任何成功。问题是:我的任务要求我从文本文件中读取几行文本并将其存储在数组中。

然而,其中一条线有明显的差距'或者我假设的几个空格(用这里的语音标记表示)给我带来了问题。

以下是文本文件的示例:

jy1 10 10 10 10 10

mp1 6 5 6 " " 7 5

ls1 9 7 12 14 15

mp2 10 12 15 15 14

lb1 12 12 12 12 12

这是我的代码:

try {
    FileReader reader= new FileReader(attendancesFile.txt);
    String line="";
    Scanner in=new Scanner(reader);

// reading from file line by line
    while (in.hasNextLine())    {
        line=in.nextLine();
        // splitting line read in separate words
        String tokens[]=line.split(" ");

        // creates an array of attendances 
        // using 5 separate attendances represented as integer values from file
        String id= tokens [0];
        int attend1= Integer.parseInt(tokens [1]);
        int attend2= Integer.parseInt(tokens [2]);
        int attend3= Integer.parseInt(tokens [3]);
        int attend4= Integer.parseInt(tokens [4]);
        int attend5= Integer.parseInt(tokens [5]);
        int [] attend= {attend1, attend2, attend3, attend4, attend5};

        // uses FP method to find Fitness Class with given ID
        // sets the attendance for Fitness Class with given ID
        fp.classByID(id).setAttendance(attend);
    } 
    reader.close();
    in.close();
}   
catch (IOException e)   {
    System.err.println("Reading from file error.");
}

理想情况下,我应该有5个数组,每个数组存储文件每行的5个整数。然后,我将这些数组传递给另一个类,其中一个方法将此int数组添加到对象数组中。

然而,它给了我一个错误:线程中的异常" main" java.lang.NumberFormatException:对于输入字符串:"" ,我假设是由于读取空白并将其添加到数组中。我已经测试过打印出每个阵列&似乎第四个阵列只有4个元素&一片空白。

1 个答案:

答案 0 :(得分:1)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div>
    <div class="target" data-post-id="1">a</div>
  </div>
  <div>
    <div class="target" data-post-id="2">b</div>
  </div>
  <div>
    <div class="target" data-post-id="1">a</div>
  </div>
  <div>
    <div class="target" data-post-id="1">a</div>
  </div>
  <div>
    <div class="target" data-post-id="2">b</div>
  </div>
</div>

这仅限于一个空白区域。 将其更改为

String tokens[]=line.split(" ");

这是任何数量的空白

This是不同正则表达式模式合成的有用指南。

String tokens[]=line.split("\\s+"); - 匹配单个空格字符

\\s - 匹配一个或多个空格字符的序列。