import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class database {
String fileName;
Scanner input;
String data[][];
List<String> records;
public database(String fileName) {
fileName = "C:/Users/lucifer/Desktop/input.txt";
}
public void openFile() {
try {
input = new Scanner(new File("C:/Users/lucifer/Desktop/input.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readRecords() {
// Read all lines (records) from the file into an ArrayList
records = new ArrayList<String>();
try {
while (input.hasNext())
records.add(input.nextLine());
System.out.println(records);
} catch (Exception e) {
// TODO: handle exception
}
}
public void parseFields() {
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = records.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row = 0;
for (String record : records) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row] = new String[cols]; // create columns for current row
int col = 0;
while (tokens.hasMoreTokens()) {
data[row][col] = tokens.nextToken().trim();
// System.out.print(data[row][col] + " ");
col++;
}
}
}
public static void main(String[] args) {
database file1 = new database(null);
file1.openFile();
file1.readRecords();
file1.parseFields();
printMatrix(file1.data);
}
static void printMatrix(String[][] grid) {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++)
System.out.print(grid[r][c] + " ");
System.out.println();
}
}
}
在這裏我解析逗號分隔的文件使用掃描儀。 爲什麼這段代碼在打印數據數組時拋出異常??錯誤解析文件 - 運行時錯誤
有什麼異常? – DevZer0
什麼例外和*哪裏*精確? –
請更新您的文章,確切的錯誤/例外 – sanbhat