Skip to content

Commit d4805af

Browse files
guang-googleAndroid (Google) Code Review
authored andcommitted
Merge "use BufferedInputStream in readTextFile" into jb-mr1-dev
2 parents 0c63d78 + 9061981 commit d4805af

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

core/java/android/os/FileUtils.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package android.os;
1818

19+
import java.io.BufferedInputStream;
1920
import java.io.ByteArrayOutputStream;
2021
import java.io.File;
2122
import java.io.FileInputStream;
@@ -91,7 +92,7 @@ public static boolean copyFile(File srcFile, File destFile) {
9192
}
9293
return result;
9394
}
94-
95+
9596
/**
9697
* Copy data from a source stream to destFile.
9798
* Return true if succeed, return false if failed.
@@ -143,12 +144,16 @@ public static boolean isFilenameSafe(File file) {
143144
*/
144145
public static String readTextFile(File file, int max, String ellipsis) throws IOException {
145146
InputStream input = new FileInputStream(file);
147+
// wrapping a BufferedInputStream around it because when reading /proc with unbuffered
148+
// input stream, bytes read not equal to buffer size is not necessarily the correct
149+
// indication for EOF; but it is true for BufferedInputStream due to its implementation.
150+
BufferedInputStream bis = new BufferedInputStream(input);
146151
try {
147152
long size = file.length();
148153
if (max > 0 || (size > 0 && max == 0)) { // "head" mode: read the first N bytes
149154
if (size > 0 && (max == 0 || size < max)) max = (int) size;
150155
byte[] data = new byte[max + 1];
151-
int length = input.read(data);
156+
int length = bis.read(data);
152157
if (length <= 0) return "";
153158
if (length <= max) return new String(data, 0, length);
154159
if (ellipsis == null) return new String(data, 0, max);
@@ -161,7 +166,7 @@ public static String readTextFile(File file, int max, String ellipsis) throws IO
161166
if (last != null) rolled = true;
162167
byte[] tmp = last; last = data; data = tmp;
163168
if (data == null) data = new byte[-max];
164-
len = input.read(data);
169+
len = bis.read(data);
165170
} while (len == data.length);
166171

167172
if (last == null && len <= 0) return "";
@@ -178,12 +183,13 @@ public static String readTextFile(File file, int max, String ellipsis) throws IO
178183
int len;
179184
byte[] data = new byte[1024];
180185
do {
181-
len = input.read(data);
186+
len = bis.read(data);
182187
if (len > 0) contents.write(data, 0, len);
183188
} while (len == data.length);
184189
return contents.toString();
185190
}
186191
} finally {
192+
bis.close();
187193
input.close();
188194
}
189195
}

0 commit comments

Comments
 (0)