[英]How can I determine the number of bytes of each line of a file in java?
我有一個很大的文本文件。 我想確定每行的字節數並將其保存在另一個文件中。
使用java.io.BufferedReader,您可以輕松地將每一行讀取為單獨的String。 一行使用的字節數取決於所使用的編碼。 對於簡單的ASCII編碼,您可以簡單地使用String的長度,因為每個字符占用一個字節。 對於UTF-8這樣的多字節編碼,您將需要一種更復雜的方法。
以下代碼摘錄
byte[] chunks = null;
BufferedReader in =
new BufferedReader (new InputStreamReader(new FileInputStream(path +"/"+filePath),"UTF-8"));
String eachLine = "";
while( (eachLine = in.readLine()) != null)
{
chunks = eachLine.getBytes("UTF-8");
System.out.println(chunks.length);
}
創建一個循環:
如果您對大文件中“行”的組成有一些定義,則可以簡單地逐字節遍歷文件,並且在每次出現行尾或行開始時,您都可以記住當前索引。
例如,如果您有一個unix文本文件(即\\n
作為行定界符),則可能如下所示:
/**
* a simple class encapsulating information about a line in a file.
*/
public static class LineInfo {
LineInfo(number, start, end) {
this.lineNumber = number;
this.startPos = start;
this.endPos = end;
this.length = endPos - startPos;
}
/** the line number of the line. */
public final long lineNumber;
/** the index of the first byte of this line. */
public final long startPos;
/** the index after the last byte of this line. */
public final long endPos;
/** the length of this line (not including the line separators surrounding it). */
public final long length;
}
/**
* creates an index of a file by lines.
* A "line" is defined by a group of bytes between '\n'
* bytes (or start/end of file).
*
* For each line, a LineInfo element is created and put into the List.
* The list is sorted by line number, start positions and end positions.
*/
public static List<LineInfo> indexFileByLines(File f)
throws IOException
{
List<LineInfo> infos = new ArrayList<LineInfo>();
InputStream in = new BufferedInputStream(new FileInputStream(f));
int b;
for(long index = 0, lastStart = 0, lineNumber = 0;
(b = in.read()) >= 0 ;
index++)
{
if(b == '\n') {
LineInfo info = new LineInfo(lineNumber, lastStart, index);
infos.add(info);
lastStart = index + 1;
lineNumber ++;
}
}
return infos;
}
這樣可以避免將字節轉換為char,從而避免任何編碼問題。 它仍然取決於行分隔符是否為\\n
但可以有一個參數將其賦予該方法。
(對於使用\\r\\n
作為分隔符的DOS / Windows文件,條件要復雜一些,因為我們要么必須存儲前一個字節,要么對下一個字節進行前瞻。)
為了更容易使用,也許不是列表,而是一對(或三對) SortedMap<Long, LineInfo>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.