很抱歉,如果我的代码看起来不好,我在编程方面经验不足。我需要从.txt传输文本,格式为:Date-Name-Address-etc. ..
我正在读取文件,然后用String.split(“ - ”)拆分字符串。我遇到了循环问题。
try{
File file = new File("testwrite.txt");
Scanner scan = new Scanner(file);
String[] test = scan.nextLine().split("-");
while(r<100){
while(c<6){
data[r][c] = test[c];
test = scan.nextLine().split("-");
c++;
}
r++;
c = 0 ;
}
System.out.println(data[1][5]);
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
答案 0 :(得分:2)
二维数组只是“数组数组”,因此您可以直接使用split
结果来存储一行数据。
File file = new File("testwrite.txt");
Scanner scanner = new Scanner(file);
final int maxLines = 100;
String[][] resultArray = new String[maxLines][];
int linesCounter = 0;
while (scanner.hasNextLine() && linesCounter < maxLines) {
resultArray[linesCounter] = scanner.nextLine().split("-");
linesCounter++;
}
答案 1 :(得分:0)
看起来你经常调用scan.nextLine()。每次调用scan.nextLine()时,它都会使扫描程序超过当前行。假设您的文件有100行,每行有6个&#34;条目&#34; (由&#34; - &#34;分隔),我会将test = scan.nextLine().split("-");
移动到while循环的末尾(但仍然在循环内),以便每行调用一次。
编辑...
建议的解决方案: 给定表单中的文件,
A-B-C-X-Y-Z
A-B-C-X-Y-Z ......(总共100次)
使用此代码:
try{
File file = new File("testwrite.txt");
Scanner scan = new Scanner(file);
String[] test = scan.nextLine().split("-");
while(r<100){
while(c<6){
data[r][c] = test[c];
c++;
}
r++;
c = 0 ;
test = scan.nextLine().split("-");
}
System.out.println(data[1][5]);
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
然后使用data [line] [index]访问您的数据。
答案 2 :(得分:0)
我使用以下内容拆分制表符分隔文件:
BufferedReader reader = new BufferedReader(new FileReader(path));
int lineNum = 0; //Use this to skip past a column header, remove if you don't have one
String readLine;
while ((readLine = reader.readLine()) != null) { //read until end of stream
if (lineNum == 0) {
lineNum++; //increment our line number so we start with our content at line 1.
continue;
}
String[] nextLine = readLine.split("\t");
for (int x = 0; x < nextLine.length; x++) {
nextLine[x] = nextLine[x].replace("\'", ""); //an example of using the line to do processing.
...additional file processing logic here...
}
}
同样,在我的实例中,我正在拆分标签(\ t),但除了换行符之外,您可以轻松地拆分 - 或任何其他字符。
每The Javadoc for readline() A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
。
根据需要将线条拆分后,只需将它们分配给阵列即可。