java中使用Files.readLines()處理文本中行數據方式
使用Files.readLines()處理文本中行數據
開發(fā)中遇到對數據庫導出到文件里的數據進行處理,然后對處理后的數據再重新寫回文件中,在這個過程中使用到了Files.readLines()方法
/**
*
* @param file : existed file
* @throws IOException
*/
public void lineProcess(File file) throws IOException {
Files.readLines(file, Charset.defaultCharset(), new LineProcessor() {
File outFile = new File("outfile");//處理后的數據輸出文件
List<String> lines = new ArrayList<String>();
@Override
public boolean processLine(String line) throws IOException {
String newLine = "";
//file中的 line數據格式:name,age,address -> NAME,AGE,ADDRESS,
String[] contents = line.split(",");
for (int i=0;i<contents.length;i++){
newLine.concat(contents[i].toLowerCase());
}
lines.add(newLine);
//將處理后的數寫入新的文件 outFile
FileUtils.writeLines(outFile,lines,true);
lines.clear();
return true;
}
@Override
public Object getResult() {
try{
FileUtils.writeLines(outFile,lines,true);
}catch (Exception e){
e.getCause();
}
lines.clear();
return null;
}
});
}
方法中的LineProcessor()實現對每一行數據處理邏輯。
依賴guava
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
被readLine()折騰了一把
雖然寫IO方面的程序不多,但BufferedReader/BufferedInputStream倒是用過好幾次的,原因是:
它有一個很特別的方法:readLine(),使用起來特別方便,每次讀回來的都是一行,省了很多手動拼接buffer的瑣碎;
它比較高效,相對于一個字符/字節(jié)地讀取、轉換、返回來說,它有一個緩沖區(qū),讀滿緩沖區(qū)才返回;一般情況下,都建議使用它們把其它Reader/InputStream包起來,使得讀取數據更高效。
對于文件來說,經常遇到一行一行的,特別相符情景。
這次是在藍牙開發(fā)時,使用兩個藍牙互相傳數據(即一個發(fā)一個收),bluecove這個開源組件已經把數據讀取都封裝成InputStream了,也就相當于平時的IO讀取了,很自然就使用起readLine()來了。
發(fā)數據
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.openOutputStream()));
int i = 1;
String message = "message " + i;
while(isRunning) {
output.write(message+"/n");
i++;
}
讀數據
BufferedReader input = new BufferedReader(new InputStreamReader(m_conn.openInputStream()));
String message = "";
String line = null;
while((line = m_input.readLine()) != null) {
message += line;
}
System.out.println(message);
上面是代碼的節(jié)選,使用這段代碼會發(fā)現寫數據時每次都成功,而讀數據側卻一直沒有數據輸出(除非把流關掉)。經過折騰,原來這里面有幾個大問題需要理解:
誤以為readLine()是讀取到沒有數據時就返回null(因為其它read方法當讀到沒有數據時返回-1),而實際上readLine()是一個阻塞函數,當沒有數據讀取時,就一直會阻塞在那,而不是返回null;因為readLine()阻塞后,System.out.println(message)這句根本就不會執(zhí)行到,所以在接收端就不會有東西輸出。要想執(zhí)行到System.out.println(message),一個辦法是發(fā)送完數據后就關掉流,這樣readLine()結束阻塞狀態(tài),而能夠得到正確的結果,但顯然不能傳一行就關一次數據流;另外一個辦法是把System.out.println(message)放到while循環(huán)體內就可以。
readLine()只有在數據流發(fā)生異?;蛘吡硪欢吮籧lose()掉時,才會返回null值。
如果不指定buffer大小,則readLine()使用的buffer有8192個字符。在達到buffer大小之前,只有遇到"/r"、"/n"、"/r/n"才會返回。
readLine()的實質(下面是從JDK源碼摘出來的)
String readLine(boolean ignoreLF) throws IOException {
StringBuffer s = null;
int startChar;
synchronized (lock) {
ensureOpen();
boolean omitLF = ignoreLF || skipLF;
bufferLoop:
for (;;) {
if (nextChar >= nChars)
fill(); //在此讀數據
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
......//其它
}
private void fill() throws IOException {
..../其它
int n;
do {
n = in.read(cb, dst, cb.length - dst); //實質
} while (n == 0);
if (n > 0) {
nChars = dst + n;
nextChar = dst;
}
}
從上面看出,readLine()是調用了read(char[] cbuf, int off, int len) 來讀取數據,后面再根據"/r"或"/n"來進行數據處理。
在Java I/O書上也說了:
public String readLine() throws IOException
This method returns a string that contains a line of text from a text file. /r, /n, and /r/n are assumed to be line breaks and are not included in the returned string. This method is often used when reading user input from System.in, since most platforms only send the user's input to the running program after the user has typed a full line (that is, hit the Return key).
readLine() has the same problem with line ends that DataInputStream's readLine() method has; that is, the potential to hang on a lone carriage return that ends the stream . This problem is especially acute on networked connections, where readLine() should never be used.
小結,使用readLine()一定要注意
讀入的數據要注意有/r或/n或/r/n
沒有數據時會阻塞,在數據流異?;驍嚅_時才會返回null
使用socket之類的數據流時,要避免使用readLine(),以免為了等待一個換行/回車符而一直阻塞
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java SpringBoot集成ChatGPT實現AI聊天
ChatGPT已經組件放開了,現在都可以基于它寫插件了,也許可以用它結合文字語音開發(fā)一個老人小孩需要的智能的說話陪伴啥的,這篇文章就介紹SpringBoot結合ChatGPT實現AI聊天感興趣的同學可以借鑒一下2023-04-04

