且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在字段中有换行符和逗号的情况下逐行读取csv文件

更新时间:2023-02-19 15:54:01

您可以将整个文件读入String变量,然后使用String.replaceAll()替换所需的字符:-

You can read the entire file into a String variable and then use String.replaceAll() to replace the characters as you want:-

    File file = new File("abc.csv");
    FileInputStream fis = null;
    fis = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    fis.read(data);
    fis.close();
    String str = new String(data, "UTF-8");

然后替换字符串中的字符:-

And then replace characters in the String:-

str = str.replaceAll("\r\n", " ");
str = str.replaceAll("[,]", ";");
System.out.println(str);

然后您可以使用新的String创建一个新文件或覆盖现有文件

Then you can create a new file or overwrite the existing file using the new String