Java 将 .txt 解析为 .csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22526679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:15:49  来源:igfitidea点击:

Parse .txt to .csv

javaparsingcsv

提问by user3333587

Is it possible to create a Java program which recognizes the text in a .txt file and write it in a .csv file? If yes,how would you start with such a problem?

是否可以创建一个 Java 程序来识别 .txt 文件中的文本并将其写入 .csv 文件中?如果是,你会如何从这样的问题开始?

My .txt file is Text1 |Text 2 so I could somehow get the char "|" and split it into two cells.

我的 .txt 文件是 Text1 |Text 2 所以我可以以某种方式得到字符“|” 并将其分成两个单元格。

采纳答案by Boris the Spider

This is very simple in Java 8:

这在 Java 8 中非常简单:

public static void main(String[] args) throws Exception {
    final Path path = Paths.get("path", "to", "folder");
    final Path txt = path.resolve("myFile.txt");
    final Path csv = path.resolve("myFile.csv");
    try (
            final Stream<String> lines = Files.lines(txt);
            final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
        lines.map((line) -> line.split("\|")).
                map((line) -> Stream.of(line).collect(Collectors.joining(","))).
                forEach(pw::println);
    }
}

First you get your files at Pathobjects.
Then you open a PrintWriterto your destination Path.

首先,您在Path对象中获取文件。
然后你打开一个PrintWriter到你的目的地Path

Now you do some Java 8 stream processing with lambdas:

现在您使用 lambda 进行一些 Java 8 流处理:

  • Files.lines(txt)streams the lines from the file
  • map((line) -> line.split("\\|"))splits each line to a String[]on |
  • map((line) -> Stream.of(line).collect(Collectors.joining(",")))joins the individual String[]again using ,
  • forEach(pw::println)writes the new lines to the destination file.
  • Files.lines(txt)流式传输文件中的行
  • map((line) -> line.split("\\|"))将每个线到一个String[]|
  • map((line) -> Stream.of(line).collect(Collectors.joining(",")))加入个人String[]再次使用,
  • forEach(pw::println)将新行写入目标文件。

Using import static:

使用import static

    try (
            final Stream<String> lines = Files.lines(txt);
            final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
        lines.map((line) -> line.split("\|")).
                map((line) -> Stream.of(line).collect(joining(","))).
                forEach(pw::println);
    }

As Java 8 was released only yesterday here is a Java 7 solution:

由于 Java 8 是昨天才发布的,这里有一个 Java 7 解决方案:

public static void main(String[] args) throws Exception {
    final Path path = Paths.get("path", "to", "folder");
    final Path txt = path.resolve("myFile.txt");
    final Path csv = path.resolve("myFile.csv");
    final Charset utf8 = Charset.forName("UTF-8");
    try (
            final Scanner scanner = new Scanner(Files.newBufferedReader(txt, utf8));
            final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
        while (scanner.hasNextLine()) {
            pw.println(scanner.nextLine().replace('|', ','));
        }
    }
}

Again, with import static:

再次,与import static

    try (
            final Scanner scanner = new Scanner(newBufferedReader(txt, utf8));
            final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
        while (scanner.hasNextLine()) {
            pw.println(scanner.nextLine().replace('|', ','));
        }
    }

回答by Wojtek Owczarczyk

You first need to How do I create a Java string from the contents of a file?.

您首先需要了解如何从文件内容创建 Java 字符串?.

Then you can take advantage of How to split a string in Javaand use |as the delimiter.

然后你可以利用How to split a string in Java|用作分隔符。

As the last step you can use the Joinerto create the final Stringand store it using How do I save a String to a text file using Java?.

作为最后一步,您可以使用Joiner创建最终String并使用How do I save a String to a text file using Java? .

回答by Markus

Yes it is possible. To accomplish your task read about Input-and OutputStreams.

对的,这是可能的。要完成您的任务,请阅读Input-OutputStreams

Start with a simple example. Read a line of text from a file and print it out on the console. Then do it the other way - write a line of text into a file.

从一个简单的例子开始。从文件中读取一行文本并将其打印在控制台上。然后以另一种方式执行 - 将一行文本写入文件。

The experience you get through these examples will help to accomplish your task.

您通过这些示例获得的经验将有助于完成您的任务。

回答by Jay Dharmendra Solanki

Yes it is very much possible. Replace | by , and write it to a csv

是的,这是很有可能的。替换 | by ,并将其写入 csv

public class NewClass {

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

   String data = "one|two|three|four"+"\n"+
           "one|two|three|four";
   //Use a BufferedReader to read from actual Text file
    String csv = data.replace("|", ",");
    System.out.println(csv);

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("MyCSV.csv")));
    out.println(csv);
    out.close();
}
}

Output

输出

run:
one,two,three,four
one,two,three,four
BUILD SUCCESSFUL (total time: 0 seconds)

回答by Shekhar Khairnar

try this may help

试试这可能有帮助

    public class Test {

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

        FileWriter writer = null;
        File file = new File("d:/sample.txt");
        Scanner scan = new Scanner(file);
        File file2 = new File("d:/CSV.csv");
        file.createNewFile();
        writer = new FileWriter(file2);

        while (scan.hasNext()) {
            String csv = scan.nextLine().replace("|", ",");
            System.out.println(csv);
            writer.append(csv);
            writer.append("\n");
            writer.flush();
        }
    }
}

sample.txt:-

示例.txt:-

  He|looked|for|a|book.

  He|picked|up|the|book.

回答by Geoff Williams

Commons CSV is useful for handling CSV output in your Java code too - in particular it takes care of gotchas such as quoting, etc:

Commons CSV 也可用于处理 Java 代码中的 CSV 输出 - 特别是它处理诸如引用等问题:

http://commons.apache.org/proper/commons-csv/

http://commons.apache.org/proper/commons-csv/

Also commons IO is really useful for simplifying reading/writing files too:

此外,commons IO 对于简化读/写文件也非常有用:

https://commons.apache.org/proper/commons-io/description.html

https://commons.apache.org/proper/commons-io/description.html

HTH

HTH