本帖最后由 hejinzhong 于 2014-8-6 15:57 编辑
举个例子来说:
- import java.io.*;
- public class Test7 {
- public static void main(String[] args) {
-
- readFile(new File("exercise.txt"));
- }
- public static void readFile(File fileName){
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- fis = new FileInputStream(fileName);
- fos = new FileOutputStream("hah.txt");
- byte[] buf = new byte[5];
- int len = 0;
- while((len=fis.read(buf))!=-1){
- fos.write(buf,0,len);//这句是写入文件
- System.out.print(new String(buf,0,len));//这句打印
- }
- } catch (Exception e) {
- throw new RuntimeException("读取失败");
- }
- finally{
- try {
- fis.close();
- } catch (IOException e) {
- throw new RuntimeException("读取流关闭失败");
- }
- try {
- if(fos!=null)
- fos.close();
- } catch (IOException e) {
- throw new RuntimeException("写入流关闭失败");
- }
- }
- }
- }//下面是几个对比
复制代码
|