-2

I have a problem with a simple code nd don't know how to do it; I have 3 txt files. First txt file looks like this:

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

I would like to read numbers from this txt file and save integers to one txt file and floats to another.

MarekOS
  • 33
  • 4
  • 1
    Please describe what the issue is with your code. And what is the comma in the sample, a separator or a decimal comma, is 6,7 the same as 6.7 or 6 and 7? – Joakim Danielson Nov 14 '20 at 09:22
  • Does the file can only have numbers or letters as well? Are all the integers digits or could it be >9? (looks like a good practice question) – ATT Nov 14 '20 at 09:24
  • 6,7 is the same as 6.7, file can only have numbers, integers could be >9; I'm sorry for being so imprecise – MarekOS Nov 14 '20 at 11:25
  • this code just doesn't work and I don't know why – MarekOS Nov 14 '20 at 11:26
  • @MarekOS - I have tested [this code](https://stackoverflow.com/a/64834562/10819573) to be working. You can comment below this code confirming the same if it solves your problem. – Arvind Kumar Avinash Nov 14 '20 at 13:59

2 Answers2

0

Assuming that , is also a decimal separator . it may be possible to unify this characters (replace , with .).

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");

Output

//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

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • Thank you for your help. Could you tell me where to paste the paths to the files? – MarekOS Nov 14 '20 at 12:32
  • The paths are passed as strings to `readAndWriteNumbers(String inputFile, String intNums, String dblNums)`, the first parameter is the path to the input file, the other two are the paths to the outputs. – Nowhere Man Nov 14 '20 at 13:35
0

You can do it with the following easy steps:

  1. When you read a line, split it on whitespace and get an array of tokens.
  2. While processing each token,
    • Trim any leading and trailing whitespace and then replace , with .
    • First check if the token can be parsed into an int. If yes, write it into outInt (the writer for integers). Otherwise, check if the token can be parsed into float. If yes, write it into outFloat (the writer for floats). Otherwise, ignore it.

Demo:

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();
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110