gpt4 book ai didi

java - 在java中拆分解析文本文件

转载 作者:行者123 更新时间:2023-12-01 14:33:44 59 4
gpt4 key购买 nike

所以基本上我可以使用 BUFFERED READER 读取文本文件。之后我应该拆分和解析它,在这一点上,我遇到了一个问题。

Output is: 5 2 9 1 7 3 9 2 10 11 6 3
Exception in thread "main" java.lang.NumberFormatException: For input string: "F:\Gephi\number.txt" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at javaapplication17.JavaApplication17.main(JavaApplication17.java:42) C:\Users\Asus\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 0 seconds)

我的代码是

package javaapplication17;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;




public class JavaApplication17 {

public static void main(String[] args) {

String count = "F:\\Gephi\\number.txt";

try (BufferedReader br = new BufferedReader(new FileReader(count)))
{
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
}

catch (IOException e)
{
e.printStackTrace();

}


// What is the Problem in this part? //

String[] abc = count.split("/t");
int[] intArray = new int[abc.length];

for (int i=0; i<abc.length; i++)

{

String numberAsString = abc[i];
intArray[i] = Integer.parseInt(numberAsString);


}

System.out.println("Number of integers: " + intArray.length);

System.out.println("The integers are:");
for (int number : intArray)

{

System.out.println(number);

}






}
}

我的文本文件是这样的

5   6   7
5 2 9
1 7 3
9 2 10
11 6 3

最佳答案

问题是 count 是一个包含值 "F:\\Gephi\\number.txt" 的字符串。这不会为您提供文件中的行数/列数。

String[] abc = count.split("/t");  // <------ This won't work

所以当你这样做的时候

int[] intArray = new int[abc.length];

您正在创建一个大小为 abc 的数组,它被 \t 分割,这是不正确的。


要解决您的问题,您可以将 try-catch block 更改为以下内容:

int countOfNum = 0;
try (BufferedReader br = new BufferedReader(new FileReader(count))) {
String line;
while ((line = br.readLine()) != null) {
String[] currLine = line.split("\t");
System.out.println(Arrays.toString(currLine));
countOfNum = countOfNum + currLine.length;
}
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("Total count of numbers : " +countOfNum);
  • 在上面的解决方案中,我们将每一行拆分为变量 currLine
  • 接下来使用 Arrays.toString() 我们打印出值
  • 现在使用变量 countOfNum 我们找到总数文件中的元素。

关于java - 在java中拆分解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53689936/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com