我嘗試讀取上傳文件的內容。我使用的庫是gwtupload
,它使用Apache FileUpload
庫。上傳的文件是22字節,但是當我用Scanner
或BufferedReader
讀取它時,最後一行需要很長時間才能解析。這裏是我的代碼片段與執行結果一起:讀取上傳文件內容時尺寸錯誤
代碼:
for (FileItem item : sessionFiles) {
System.out.println("FileItem.size() = " + item.getSize());
// Read with a scanner
System.out.println("Read with a Scanner");
Scanner scanner = new Scanner(item.getInputStream());
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append("\n");
System.out.println(sb.length());
}
// Read with a Reader
System.out.println("Read with a Reader");
StringBuffer sb2 = new StringBuffer();
BufferedReader reader = new BufferedReader(
new InputStreamReader(item.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
sb2.append(line).append("\n");
System.out.println(sb2.length());
// if (sb2.length() + 1 == item.getSize()) {
// break;
// }
}
for (int i = 0; i < 30; i++) {
System.out.println(String.format("%d: %c [%d]", i,
sb2.charAt(i), (int) sb2.charAt(i)));
}
System.out.println("End");
結果:
FileItem.size() = 22
Read with a Scanner
21
1047552
Read with a Reader
21
1047552
0: I [73]
1: d [100]
2: , [44]
3: D [68]
4: a [97]
5: t [116]
6: e [101]
7: , [44]
8: [32]
9: D [68]
10: e [101]
11: s [115]
12: c [99]
13: r [114]
14: i [105]
15: p [112]
16: t [116]
17: i [105]
18: o [111]
19: n [110]
20:
[10]
21:
Eclipse控制檯顯示的字符,直到29但當我粘貼控制檯,它停止從21到29,ASCII
代碼是0
。
上傳的文件來自'贏7'框,但我不認爲它應該的問題了'Scanner',因爲它會檢查所有可能的行終止符。 'private static final String LINE_SEPARATOR_PATTERN =「\ r \ n | [\ n \ r \ u2028 \ u2085 \ u0085]」;'使用'hasNextLine()'或'nextLine()'方法。 – Sydney