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

sshcrbum  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(411)

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

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {

        FileInputStream fstream = new FileInputStream("C:\\...\\t.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        FileWriter ostream = new FileWriter("C:\\...\\t2.txt");
        BufferedWriter out = new BufferedWriter(ostream);
        FileWriter ostream2 = new FileWriter("C:\\Users\\...\\t3.txt");
        BufferedWriter out2 = new BufferedWriter(ostream2);

        String str=br.readLine();

        char ch;

        for (int i=0;i<str.length();i++)
        {
            ch = str.charAt(i);

            if((ch % 1 != 0))
            {
               out2.write(ch);
            }
            else
            {
                out.write(ch);
            }
        }
        out.close();
        br.close();
        out2.close();
    }
}

你们谁能帮我一下吗?

ktecyv1j

ktecyv1j1#

假设 , 也是小数分隔符 . 可以统一这些字符(替换 ,. ).

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
1dkrff03

1dkrff032#

您可以通过以下简单步骤完成:
当你读一行的时候,把它分成空格,得到一个记号数组。
在处理每个令牌时,
修剪任何前导和尾随空格,然后替换 ,. 首先检查令牌是否可以解析为 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();
    }
}

相关问题