日期:2014-05-17  浏览次数:20617 次

JAVA读取一个文件,非得搞那么麻烦么??
读个文件而已啊,难道就没有一种办法直接提供成这种的:
byte[] bytes = new File(fileName).getBytes();
JDK为什么不封装一个这样的给用户呢?为什么一定还要自己指定长度,然后调用一大堆麻烦的代码才行?
这是为什么?

下面这些破玩意,每次都要用户自己封装么?
OutputStream os = response.getOutputStream();
File file = new File(name);
InputStream is = new FileInputStream(file);
int length = (int)file.length();
byte[] bytes = new byte[length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
  offset += numRead;
}
if (offset < bytes.length) {
  throw new IOException("Could not completely read file "+file.getName());
}
is.close();


------解决方案--------------------
用Java 1.7
Java code

Path path = Paths.get("path/to/file"); 
Files.readAllBytes(path);