字符流读:
- FileReader fr=null;
- try
- {
- fr=new FileReader("demo.txt");
- char[] n=new char[1024];
- int num=0;
- while((num=fr.read(n))!=-1)
- System.out.println(num+"<>>"+new String(n,0,num));
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- if(fr!=null)
- fr.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
-
- }
复制代码
字符流写:
- FileWriter fw=null;
- try
- {
- fw=new FileWriter("demo.txt");
- fw.write("djdklj");
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- if(fw!=null)
- fw.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
复制代码
字节流读:
- import java.io.*;
- class InputStreamDemo
- {
- public static void main(String[] args)
- {
- read_3();
- }
- public static void read_1()
- {
- FileInputStream fis=null;
- try
- {
- fis=new FileInputStream("Demo.java");
- int len=0;
- byte[] buf=new byte[1024];
- while((len=fis.read(buf))!=-1)
- {
- System.out.println(new String(buf,0,len));
- }
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- if(fis!=null)
- fis.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }
- public static void read_2()
- {
- FileInputStream fis=null;
- try
- {
- fis=new FileInputStream("Demo.java");
- int ch=0;
- while((ch=fis.read())!=-1)
- {
- System.out.println((char)ch);
- }
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- if(fis!=null)
- fis.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }
- public static void read_3()
- {
- FileInputStream fis=null;
- try
- {
- fis=new FileInputStream("Demo.java");
- byte [] buf=new byte[fis.available()];
- fis.read(buf);
- System.out.println(new String(buf));
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- if(fis!=null)
- fis.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }
- }
复制代码
字节流写:
- import java.io.*;
- class CopyPicture
- {
- public static void main(String[] args)
- {
- FileInputStream fis=null;
- FileOutputStream fos=null;
- try
- {
- fis=new FileInputStream("Desert.jpg");
- fos=new FileOutputStream("Demo.jpg");
- int len=0;
- byte[] buf=new byte[1024];
- while((len=fis.read(buf))!=-1)
- {
- fos.write(buf,0,len);
- }
- }
- catch (IOException e)
- {
- throw new RuntimeException("copy failed!");
- }
- finally
- {
- try
- {
- if(fis!=null)
- fis.close();
- if(fos!=null)
- fos.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("读取关闭失败");
- }
- }
- }
- }
复制代码 |