Java三种读取文件的方式

  • 11

Java三种读取文件的方式

字节读取方式

File file = new File(path);
FileInputStream fis = new FileInputStream(file);
int ch = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((ch = fis.read()) != -1){
  baos.write(ch);
}
baos.close();
fis.close();

字节数组读取方式

File file = new File(path);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
while((len = fis.read(buffer)) != -1){
 baos.write(buffer,0,len);
}
fis.close();
baos.close();

行级字符流读取方式

File file = new File(path);
BufferedReader br = new BufferedReader(new Filereader(file));
String string = null;
StringBuffer sb = new StringBuffer();
while((string = br.readLine()) != null){
   sb.append(string);
}
br.close();

发表评论