简单的JAVA IO

来源:互联网 发布:手机的播放软件 编辑:程序博客网 时间:2024/05/01 01:28

1、字节流:(FileInputStream,FileOutputStream);
  缺点:可能会出现乱码的问题;
  优点:可以很准确复制指定的文字和图片;
  注意事项:如果有汉字,一定要定义成字节数组类型;
       FileOutputStream这个流一定要记得关闭;
2、字符流:(FileReader,FileWriter)
       优缺点跟字节流相反;
3、处理流:(BufferedReader,BufferedWriter,BufferedInputStream,
 BufferedOutputStream)
       格式:BufferedReader br=new BufferedReader(new   FileReader(路径));
       注意事项:处理流中的套流必须字符流对字符流,字节流对字节流;

4、File类测试PPT里面的十个方法即可;

        通过File对象可以访问文件的属性。    

 public boolean canRead()  public boolean canWrite()    public boolean exists()     public boolean isDirectory()     public boolean isFile()   

 public boolean isHidden()  public long lastModified()     public long length()           public String getName()            public String getPath()

5、过滤器:
  步骤:
  第一步:实现filenamefilter这个接口并实例化accept();
  第二步:创建实现类的构造方法,为了得到我们想要的文件后缀名;
  第三步:接收我想要得到的文件或目录(getName(),indexof() );
  第四步:创建一个File类,给定一个路径和目录;
  第五步:运用File类里面的list(FilenameFilter f)这个方法,必须创建一个字符串数组类型,从list()方法里面得到要过滤后的文件后缀名;
  第六步:一维数组的遍历,for();

6、数据流(DataInputStream,DataOutputStream):
     缺点:Data流的构造只有一种(OutputSteram/InputStream的类型),所以不能通过其他  种类型来定义,具有局限性;
 优点:通过数据流的方式,读写出来的流,一定具有保护性;
7、print流(PrintWriter/PrintStream)
       功能:具有标准输入/输出流,能够把在控制台上显示的内     容复制指定文件夹下;
8、Object流:(ObjectInputStream,ObjectOutputStream 
        功能:主要用于网络编程语言,传递信息;

字节流:package com.xinbo.edu;import java.io.*;public class Test {public static void main(String[] args) {FileInputStream fis=null;FileOutputStream fos=null;try {fis=new FileInputStream("E:/myjava/file.txt");fos=new FileOutputStream("E:/myjava/mylove1.txt");byte[] b=new byte[512];int c=fis.read(b);//int c=fis.read();while(c!=-1){System.out.print(new String(b));//System.out.print((char)c);//c=fis.read();//fos.write(c);c=fis.read(b);fos.write(b);}} catch (FileNotFoundException e) {System.out.println("找不到文件!");} catch (IOException e) {System.out.println("文件读取失败!");}finally{try {fis.close();fos.close();} catch (IOException e) {System.out.println("关闭失败!");}}}}
字符流:package com.xinbo.edu;import java.io.*;public class TestReader {public static void main(String[] args) {FileReader fr=null;FileWriter fw=null;try {fr=new FileReader("E:/myjava/file.txt");fw=new FileWriter("E:/myjava/file2.txt");int b=0;b=fr.read();while(b!=-1){System.out.print((char)b);fw.write(b);b=fr.read();}} catch (FileNotFoundException e) {System.out.println("找不到文件!");} catch (IOException e) {System.out.println("读取失败!");} finally{try {fr.close();fw.close();} catch (IOException e) {System.out.println("关闭失败!");}}}}

处理流(1):package com.xinbo.edu;import java.io.*;public class TestBuffer {public static void main(String[] args) {BufferedInputStream bis=null;BufferedOutputStream bos=null;try {bis=new BufferedInputStream(new FileInputStream("E:/myjava/file.txt"));bos=new BufferedOutputStream(new FileOutputStream("E:/myjava/file8.txt"));byte[] s=new byte[100];int b=0;b=bis.read(s);while(b!=-1){System.out.print(new String(s));bos.write(s);b=bis.read(s);}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {bis.close();bos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}处理流(2):package com.xinbo.edu;import java.io.*;public class TestBufferReader {public static void main(String[] args) {BufferedReader br=null;BufferedWriter bw=null;try {br=new BufferedReader(new FileReader("E:/myjava/file.txt"));bw=new BufferedWriter(new FileWriter("E:/myjava/file79.txt"));String s=null;s=br.readLine();while(s!=null){System.out.println(s);bw.write(s);s=br.readLine();}} catch (FileNotFoundException e) {} catch (IOException e) {}finally{try {br.close();bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

过滤器:

public class TestFilet {public static void main(String[] args) {File dir=new File("f:/java");String[] names;Filter filter=new Filter(".doc");names=dir.list(filter);for(int i=0;i<names.length;i++){System.out.println(names[i]);}}}class Filter implements FilenameFilter{    private String type;    public Filter(String type){    this.type=type;    }@Overridepublic boolean accept(File dir, String name) {File file=new File(name);String filename=file.getName();return filename.indexOf(type)!=-1;}}


Object流:

package com.xinbo;public class User implements java.io.Serializable{//序列化对象private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPass() {return pass;}public void setPass(String pass) {this.pass = pass;}private String pass;}package com.xinbo;import java.net.*;import java.io.*;public class MyServer {/** * @param args */public static void main(String[] args) {MyServer ms=new MyServer();}public MyServer(){try{System.out.println("我是服务器,在3456端口监听...");ServerSocket ss=new ServerSocket(3456);Socket s=ss.accept();//以对象流的方式读取,假设客户端发送的是User的一个对象ObjectInputStream ois=new ObjectInputStream(s.getInputStream());User u=(User)ois.readObject();//输出System.out.println("从客户端接收到:"+u.getName()+" "+"密码是:"+u.getPass());}catch(Exception e){e.printStackTrace();}}}package com.xinbo;import java.net.*;import java.io.*;public class MyClient {/** * @param args */public static void main(String[] args) {MyClient mc=new MyClient(); }public  MyClient(){try{Socket s=new Socket("127.0.0.1",3456);//通过ObjectOutputStream流给服务器传送对象ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());User u=new User();u.setName("小明");u.setPass("huangyuxin");oos.writeObject(u);}catch(Exception e){ e.printStackTrace();}}}


import java.io.*;public class TestDataStream {  public static void main(String[] args) {    ByteArrayOutputStream baos =                         new ByteArrayOutputStream();     DataOutputStream dos =                         new DataOutputStream(baos);    try {      dos.writeDouble(Math.random());      dos.writeBoolean(true);      ByteArrayInputStream bais =           new ByteArrayInputStream(baos.toByteArray());      System.out.println(bais.available());      DataInputStream dis = new DataInputStream(bais);      System.out.println(dis.readDouble());      System.out.println(dis.readBoolean());      dos.close();  dis.close();    } catch (IOException e) {      e.printStackTrace();    }  }}
package IoTest;import java.io.*;public class TestPrintStream1 {   public static void main(String[] args) {    PrintStream ps = null;    try {      FileOutputStream fos =               new FileOutputStream("d:\\bak\\log.dat");      ps = new PrintStream(fos);    } catch (IOException e) {      e.printStackTrace();    }    if(ps != null){      System.setOut(ps);    }    int ln = 0;    for(char c = 0; c <= 60000; c++){      System.out.print(c+ " ");      if(ln++ >=100){ System.out.println(); ln = 0;}    }  }}


package IoTest;import java.util.*; import java.io.*;public class TestPrintStream3 {  public static void main(String[] args) {    String s = null;    BufferedReader br = new BufferedReader(                        new InputStreamReader(System.in));    try {      FileWriter fw = new FileWriter                           ("d:\\bak\\logfile.log", true); //Log4J      PrintWriter log = new PrintWriter(fw);      while ((s = br.readLine())!=null) {        if(s.equalsIgnoreCase("exit")) break;        System.out.println(s.toUpperCase());        log.println("-----");        log.println(s.toUpperCase());         log.flush();      }      log.println("==="+new Date()+"===");       log.flush();      log.close();    } catch (IOException e) {      e.printStackTrace();    }  }}