Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 读取文件中每行的第一个字符_Java_File - Fatal编程技术网

Java 读取文件中每行的第一个字符

Java 读取文件中每行的第一个字符,java,file,Java,File,我有一个以下格式的文件: 0 2 4 3 2 4 3 5 2 1 8 2 我的目标是读取每个文件的第一行并将其存储在数组中。所以最后我应该有0,3,3,1 我认为一种方法是,读取行,直到我们遇到一个空格,并将其保存在数组中…但之后它将继续读取2和4 是否有一种有效的方法可以做到这一点,我的cod如下所示: openandprint() { int i = 0; try (BufferedReader br = new BufferedReader(new FileReader("final.t

我有一个以下格式的文件:

0 2 4
3 2 4
3 5 2
1 8 2
我的目标是读取每个文件的第一行并将其存储在数组中。所以最后我应该有
0,3,3,1

我认为一种方法是,读取行,直到我们遇到一个空格,并将其保存在数组中…但之后它将继续读取2和4

是否有一种有效的方法可以做到这一点,我的cod如下所示:

openandprint()
{
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("final.txt"))) 
    {
        String line;
        while ((line = br.readLine()) != null) {
        int change2Int=Integer.parseInt(line.trim());
        figures [i] = change2Int;
        i++;
        }
    }
catch (Exception expe)
    {
    expe.printStackTrace();
    }

}
试一试

使用您的方法,您正在读取整行内容并将其解析为int,这将为您提供
NumberFormatException
,因为数字之间有空格。

使用a将使代码更加清晰:

BufferedReader br = ...;
String line = null;
while ((line = br.readLine()) != null) {
  String[] parts = line.split(" ");
  int next = Integer.parseInt(parts[0]);
  System.out.println("next: " + next);
}
private static openandprint() throws IOException {
    int i = 0;
    try (Scanner s = new Scanner("final.txt")))  {
        String line;
        while (s.hasNextLine()) {
            int change2Int = s.nextInt();
            s.nextLine(); // ignore the rest of the line
            figures [i] = change2Int;
            i++;
        }
    }
}

读整行并将第一个字符放入数组怎么样?这样有效吗?无论如何,您已经将整行读取到内存中了。这是最有意义的。如果只关心第一个整数,则无需加载整行。@Rubixus
s.nextLine()然后呢?它不会神奇地忽略线条。它仍然读取它,只是在代码中忽略了它。@Mureinik如果想让我们说只读取第二个数字?是吗possible@lecardo在
while
语句之后添加一个
s.nextInt()
,以跳过第一个数字。这是一种又快又脏的方式,介意吗?
BufferedReader br = ...;
String line = null;
while ((line = br.readLine()) != null) {
  String[] parts = line.split(" ");
  int next = Integer.parseInt(parts[0]);
  System.out.println("next: " + next);
}
private static openandprint() throws IOException {
    int i = 0;
    try (Scanner s = new Scanner("final.txt")))  {
        String line;
        while (s.hasNextLine()) {
            int change2Int = s.nextInt();
            s.nextLine(); // ignore the rest of the line
            figures [i] = change2Int;
            i++;
        }
    }
}