我有一个简单的代码问题,不知道该怎么做;我有 3 个 txt 文件。第一个 txt 文件如下所示:
1 2 3 4 5 4.5 4,6 6.8 8,9
1 3 4 5 8 9,2 6,3 6,7 8.9
我想从这个 txt 文件中读取数字并将整数保存到一个 txt 文件并浮动到另一个。
您可以通过以下简单步骤来做到这一点:
,
为.
int
. 如果是,请将其写入outInt
(整数编写器)。否则,检查令牌是否可以解析为float
. 如果是,请将其写入outFloat
(浮点数的编写器)。否则,忽略它。演示:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(new FileReader("t.txt"));
BufferedWriter outInt = new BufferedWriter(new FileWriter("t2.txt"));
BufferedWriter outFloat = new BufferedWriter(new FileWriter("t3.txt"));
String line = "";
while ((line = in.readLine()) != null) {// Read until EOF is reached
// Split the line on whitespace and get an array of tokens
String[] tokens = line.split("\\s+");
// Process each token
for (String s : tokens) {
// Trim any leading and trailing whitespace and then replace , with .
s = s.trim().replace(',', '.');
// First check if the token can be parsed into an int
try {
Integer.parseInt(s);
// If yes, write it into outInt
outInt.write(s + " ");
} catch (NumberFormatException e) {
// Otherwise, check if token can be parsed into float
try {
Float.parseFloat(s);
// If yes, write it into outFloat
outFloat.write(s + " ");
} catch (NumberFormatException ex) {
// Otherwise, ignore it
}
}
}
}
in.close();
outInt.close();
outFloat.close();
}
}
假设这,
也是一个小数分隔符.
,则可以统一此字符(替换,
为.
)。
static void readAndWriteNumbers(String inputFile, String intNums, String dblNums) throws IOException {
// Use StringBuilder to collect the int and double numbers separately
StringBuilder ints = new StringBuilder();
StringBuilder dbls = new StringBuilder();
Files.lines(Paths.get(inputFile)) // stream of string
.map(str -> str.replace(',', '.')) // unify decimal separators
.map(str -> {
Arrays.stream(str.split("\\s+")).forEach(v -> { // split each line into tokens
if (v.contains(".")) {
if (dbls.length() > 0 && !dbls.toString().endsWith(System.lineSeparator())) {
dbls.append(" ");
}
dbls.append(v);
}
else {
if (ints.length() > 0 && !ints.toString().endsWith(System.lineSeparator())) {
ints.append(" ");
}
ints.append(v);
}
});
return System.lineSeparator(); // return new-line
})
.forEach(s -> { ints.append(s); dbls.append(s); }); // keep lines in the results
// write the files using the contents from the string builders
try (
FileWriter intWriter = new FileWriter(intNums);
FileWriter dblWriter = new FileWriter(dblNums);
) {
intWriter.write(ints.toString());
dblWriter.write(dbls.toString());
}
}
// test
readAndWriteNumbers("test.dat", "ints.dat", "dbls.dat");
输出
//ints.dat
1 2 3 4 5
1 3 4 5 8
// dbls.dat
4.5 4.6 6.8 8.9
9.2 6.3 6.7 8.9