问题
I have to read a csv file line by line and change line break (alt+enter that is \n\r) with space and comas out side of fields with Ctrl+A (\001). As I try this with reading Buffered Reader, it takes line from \n and not interpret \n\r as non line break character. How can I handle this. I have to done this in java
回答1:
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);
Then you can create a new file or overwrite the existing file using the new String
回答2:
I assume you mean "\r\n", not "\n\r". Usually windows-based programs generate "\r\n" while linux-based programs use "\n".
The buffered reader normally uses the global "line.separator" setting that should be set specifically for your system.
On a sidenote: it is usually interesting to use frameworks for parsing instead of doing actual line reads because there are a lot of edge cases (like this one) that a framework usually covers.
来源:https://stackoverflow.com/questions/27373120/how-to-read-a-csv-file-line-by-line-having-line-break-and-coma-in-fields