首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

JAVA读取一个文件,非得搞那么麻烦么?解决办法

2012-09-16 
JAVA读取一个文件,非得搞那么麻烦么??读个文件而已啊,难道就没有一种办法直接提供成这种的:byte[] bytes

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); 

热点排行