简体   繁体   中英

Parser for Converting .txt file to .csv in Java

I want to convert the text file to excel file with the help of Java. The example data as like below,

12A8 3.10 0.82 0.10 06:08:57
12A8 3.07 0.82 0.14 06:08:58
12A8 3.08 0.83 0.12 06:08:59
5C12 1.92 0.66 0.47 06:08:59
12A8 3.09 0.84 0.13 06:09:00
5C12 1.95 0.66 0.50 06:09:01
12A8 3.03 0.85 0.25 06:09:01
12A8 2.98 0.84 0.31 06:09:03
12A8 2.94 0.86 0.39 06:09:03
5C12 2.03 0.70 0.56 06:09:04
12A8 2.91 0.86 0.44 06:09:04
5C12 2.05 0.70 0.57 06:09:04
12A8 3.06 0.86 0.23 06:09:05
12A8 3.00 0.86 0.31 06:09:07
12A8 2.96 0.86 0.38 06:09:08
12A8 2.93 0.79 0.41 06:09:08
12A8 3.07 0.81 0.21 06:09:09
5C12 2.07 0.69 0.60 06:09:10

As it is obvious, each column is seperated by a space.

To turn this document into a CSV file you just need to replace all the spaces with commas. Here's a way you could do it.

        final File input = new File("com/aexp/file.txt");
        List<String> output = new ArrayList<>();
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
             reader = new BufferedReader(new FileReader(input));
            String line;
            while((line = reader.readLine()) != null){
                output.add(line.replaceAll(" ", ","));
            }

            reader.close();

             writer = new BufferedWriter(new FileWriter(new File("output.txt")));
            for (String s : output) {
                writer.write(s);
                writer.newLine();
            }

            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM