3 回答

TA貢獻1804條經驗 獲得超3個贊
我會首先檢查我是否可以讀取該文件(您可以使用File.canRead()
來執行此操作)。接下來,我將編譯一個具有三個分組操作的正則表達式。然后我會使用BufferedReader.readLine()
來讀取文本行;read()
調用返回單個字符。然后它只剩下解析匹配的行。而且我認為吞下原始異常只是為了重新刪除它(事實上,你以當前的方式丟失了所有堆棧跟蹤信息)。我看不出有什么意義。把這些放在一起,
public static void processFile(String inputFilePath) throws IOException {
File f = new File(inputFilePath);
if (!f.canRead()) {
throw new IllegalArgumentException("Error reading file.");
}
// Initialize required variables for processing the file
try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) {
Pattern p = Pattern.compile("^\\s*(\\d+)\\s+(\\d+)\\s+(\\d.+)$");
String line;
while ((line = fileReader.readLine()) != null) {
Matcher m = p.matcher(line);
if (m.matches()) {
int start = Integer.parseInt(m.group(1));
int end = Integer.parseInt(m.group(2));
double weight = Double.parseDouble(m.group(3));
System.out.printf("start=%d, end=%d, weight=%.2f%n", start, end, weight);
}
}
}
}

TA貢獻1877條經驗 獲得超1個贊
切換到readLine并使用掃描儀:
public static void processFile(String inputFilePath) throws IOException {
// Check to see if file input is valid
if (inputFilePath == null || inputFilePath.trim()
.length() == 0) {
throw new IllegalArgumentException("Error reading file.");
}
// Initialize required variables for processing the file
String line;
int count = 0;
// We are reading from the file, so we can use FileReader and InputStreamReader.
try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) {
// Read numbers from the line
while ((line = fileReader.readLine()) != null) { // Stop reading file when -1 is reached
Scanner scanner = new Scanner(line);
// First input is the start
int start = scanner.nextInt();
if (start == -1) {
break;
}
// Second input is the end
int end = scanner.nextInt();
// Third input is the weight
double weight = scanner.nextDouble();
// do stuff
}
} catch (IOException e) {
throw new IOException("Error processing the file.");
}
}

TA貢獻1866條經驗 獲得超5個贊
而不是使用,你可以只是使用然后使用分裂與你的分隔符是三個空格,我想?readreadLine
try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) {
String line;
while(!(line = fileReader.readLine()).equals("-1")) {
String[] edge = line.split(" ");
int start = Integer.parseInt(edge[0]);
int end = Integer.parseInt(edge[1]);
double weight = Double.parseDouble(edge[2]);
}
} catch (IOException e) {
e.printStackTrace();
}
添加回答
舉報