在txt文件中查找整数和浮点数

Find Integers and float numbers in txt file

我对一段简单的代码有疑问,但不知道该怎么做; 我有 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 文件并将浮点数保存到另一个文件。

假设,也是一个小数点分隔符.,也许可以统一这些字符(将,替换为.)。

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

您可以通过以下简单的步骤完成:

  1. 当您读取一行时,将其拆分为空格并获得一个标记数组。
  2. 在处理每个令牌时,
    • Trim 任何前导和尾随空格,然后将 , 替换为 .
    • 首先检查令牌是否可以解析为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();
    }
}