首页 > 解决方案 > 在 txt 文件中查找整数和浮点数

问题描述

我有一个简单的代码问题,不知道该怎么做;我有 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 文件并浮动到另一个。

标签: javafiletxt

解决方案


您可以通过以下简单步骤来做到这一点:

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

推荐阅读