java;IO流

/**
* 字节流
* 读文件内容
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       String fileName="D:"+File.separator+"hello.txt";
       File f=new File(fileName);
       InputStream in=new FileInputStream(f);
       byte[] b=new byte[1024];
       in.read(b);
       in.close();
       System.out.println(new String(b));
    }
}
======================================================================
/**
* 字节流
* 读文件内容
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       String fileName="D:"+File.separator+"hello.txt";
       File f=new File(fileName);
       InputStream in=new FileInputStream(f);
       byte[] b=new byte[1024];
       int len=in.read(b);
       in.close();
       System.out.println("读入长度为:"+len);
       System.out.println(new String(b,0,len));
    }
}

/**
* 字节流
* 读文件内容,节省空间
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       String fileName="D:"+File.separator+"hello.txt";
       File f=new File(fileName);
       InputStream in=new FileInputStream(f);
       byte[] b=new byte[(int)f.length()];
       in.read(b);
       System.out.println("文件长度为:"+f.length());
       in.close();
       System.out.println(new String(b));
    }
}
/**
* 字节流
* 读文件内容,节省空间
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       String fileName="D:"+File.separator+"hello.txt";
       File f=new File(fileName);
       InputStream in=new FileInputStream(f);
       byte[] b=new byte[(int)f.length()];
       for (int i = 0; i < b.length; i++) {
           b[i]=(byte)in.read();
       }
       in.close();
       System.out.println(new String(b));
    }
}
/**
* 字节流
*读文件
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       String fileName="D:"+File.separator+"hello.txt";
       File f=new File(fileName);
       InputStream in=new FileInputStream(f);
       byte[] b=new byte[1024];
       int count =0;
       int temp=0;
       while((temp=in.read())!=(-1)){
           b[count++]=(byte)temp;
       }
       in.close();
       System.out.println(new String(b));
    }
}
======================================================================
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
public class DataOutputStreamDemo{
   public static void main(String[] args) throws IOException{
       File file = new File("d:" + File.separator +"hello.txt");
       DataInputStream input = new DataInputStream(new FileInputStream(file));
       char[] ch = new char[10];
       int count = 0;
       char temp;
       while((temp = input.readChar()) != 'C'){
           ch[count++] = temp;
       }
       System.out.println(ch);
    }
}
======================================================================import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;
 
/**
* 回退流操作
* */
public class PushBackInputStreamDemo{
    public static void main(String[] args) throwsIOException{
       String str = "hello,rollenholt";
       PushbackInputStream push = null;
       ByteArrayInputStream bat = null;
       bat = new ByteArrayInputStream(str.getBytes());
       push = new PushbackInputStream(bat);
       int temp = 0;
       while((temp = push.read()) != -1){
           if(temp == ','){
                push.unread(temp);
                temp = push.read();
                System.out.print("(回退" +(char) temp + ") ");
           }else{
                System.out.print((char) temp);
           }
       }
    }
}
======================================================================
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;
 
/**
* 回退流操作
* */
public class PushBackInputStreamDemo{
    public static void main(String[] args) throwsIOException{
       String str = "hello,rollenholt";
       PushbackInputStream push = null;
       ByteArrayInputStream bat = null;
       bat = new ByteArrayInputStream(str.getBytes());
       push = new PushbackInputStream(bat);
       int temp = 0;
       while((temp = push.read()) != -1){
           if(temp == ','){
                push.unread(temp);
                temp = push.read();
                System.out.print("(回退" +(char) temp + ") ");
           }else{
                System.out.print((char) temp);
           }
       }
    }
}
/**
* 字节流
* 向文件中一个字节一个字节的写入字符串
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       String fileName="D:"+File.separator+"hello.txt";
       File f=new File(fileName);
       OutputStream out =new FileOutputStream(f);
       String str="Hello World!!";
       byte[] b=str.getBytes();
       for (int i = 0; i < b.length; i++) {
           out.write(b[i]);
       }
       out.close();
    }
}
/**
* 字节流
* 向文件中追加新内容:
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       String fileName="D:"+File.separator+"hello.txt";
       File f=new File(fileName);
       OutputStream out =new FileOutputStream(f,true);//true表示追加模式,否则为覆盖
       String str="Rollen";
       //String str="\r\nRollen"; 可以换行
       byte[] b=str.getBytes();
       for (int i = 0; i < b.length; i++) {
           out.write(b[i]);
       }
       out.close();
    }
}
/**
* 文件的复制
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       if(args.length!=2){
           System.out.println("命令行参数输入有误,请检查");
           System.exit(1);
       }
       File file1=new File(args[0]);
       File file2=new File(args[1]);
        
       if(!file1.exists()){
           System.out.println("被复制的文件不存在");
           System.exit(1);
       }
       InputStream input=new FileInputStream(file1);
       OutputStream output=new FileOutputStream(file2);
       if((input!=null)&&(output!=null)){
           int temp=0;
           while((temp=input.read())!=(-1)){
                output.write(temp);
           }
       }
       input.close();
       output.close();
    }
}
/**
* 使用内存操作流将一个大写字母转化为小写字母
* */
import java.io.*;
class hello{
   public static void main(String[] args) throws IOException {
       String str="ROLLENHOLT";
       ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());
       ByteArrayOutputStream output=new ByteArrayOutputStream();
       int temp=0;
       while((temp=input.read())!=-1){
           char ch=(char)temp;
           output.write(Character.toLowerCase(ch));
       }
       String outStr=output.toString();
       input.close();
       output.close();
       System.out.println(outStr);
    }
}
/**
* 验证管道流
* */
import java.io.*;
 
/**
* 消息发送类
* */
class Send implements Runnable{
   private PipedOutputStream out=null;
   public Send() {
       out=new PipedOutputStream();
    }
   public PipedOutputStream getOut(){
       return this.out;
    }
   public void run(){
       String message="hello , Rollen";
       try{
           out.write(message.getBytes());
       }catch (Exception e) {
           e.printStackTrace();
       }try{
           out.close();
       }catch (Exception e) {
           e.printStackTrace();
       }
    }
}
 
/**
* 接受消息类
* */
class Recive implements Runnable{
   private PipedInputStream input=null;
   public Recive(){
       this.input=new PipedInputStream();
    }
   public PipedInputStream getInput(){
       return this.input;
    }
   public void run(){
       byte[] b=new byte[1000];
       int len=0;
       try{
           len=this.input.read(b);
       }catch (Exception e) {
           e.printStackTrace();
       }try{
           input.close();
       }catch (Exception e) {
           e.printStackTrace();
       }
       System.out.println("接受的内容为 "+(new String(b,0,len)));
    }
}
/**
* 测试类
* */
class hello{
   public static void main(String[] args) throws IOException {
       Send send=new Send();
       Recive recive=new Recive();
        try{
//管道连接
           send.getOut().connect(recive.getInput());
       }catch (Exception e) {
           e.printStackTrace();
       }
       new Thread(send).start();
       new Thread(recive).start();
    }
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
/**
* 一次性压缩多个文件
* */
public class ZipOutputStreamDemo2{
   public static void main(String[] args) throws IOException{
       // 要被压缩的文件夹
       File file = new File("d:" + File.separator +"temp");
       File zipFile = new File("d:" + File.separator + "zipFile.zip");
       InputStream input = null;
       ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
                zipFile));
       zipOut.setComment("hello");
       if(file.isDirectory()){
           File[] files = file.listFiles();
           for(int i = 0; i < files.length; ++i){
                input = newFileInputStream(files[i]);
                zipOut.putNextEntry(newZipEntry(file.getName()
                        + File.separator +files[i].getName()));
               int temp = 0;
                while((temp = input.read()) !=-1){
                    zipOut.write(temp);
                }
                input.close();
           }
       }
       zipOut.close();
    }
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
 
/**
* 解压缩文件(压缩文件中只有一个文件的情况)
* */
public class ZipFileDemo2{
   public static void main(String[] args) throws IOException{
       File file = new File("d:" + File.separator +"hello.zip");
       File outFile = new File("d:" + File.separator +"unZipFile.txt");
       ZipFile zipFile = new ZipFile(file);
       ZipEntry entry =zipFile.getEntry("hello.txt");
       InputStream input = zipFile.getInputStream(entry);
       OutputStream output = new FileOutputStream(outFile);
       int temp = 0;
       while((temp = input.read()) != -1){
           output.write(temp);
       }
       input.close();
       output.close();
    }
}
----------------------------------------------------------------------import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/**
* 使用缓冲区从键盘上读入内容
* */
public class BufferedReaderDemo{
   public static void main(String[] args){
       BufferedReader buf = new BufferedReader(
                newInputStreamReader(System.in));
       String str = null;
       System.out.println("请输入内容");
       try{
           str = buf.readLine();
       }catch(IOException e){
           e.printStackTrace();
       }
       System.out.println("你输入的内容是:" + str);
    }
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
 
/**
*Scanner的小例子,从文件中读内容
* */
public class ScannerDemo{
   public static void main(String[] args){
 
       File file = new File("d:" + File.separator +"hello.txt");
       Scanner sca = null;
       try{
           sca = new Scanner(file);
       }catch(FileNotFoundException e){
           e.printStackTrace();
       }
       String str = sca.next();
       System.out.println("从文件中读取的内容是:" + str);
    }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~* 列出指定目录的全部内容
* */
import java.io.*;
class hello{
   public static void main(String[] args) {
       String fileName="D:"+File.separator;
       File f=new File(fileName);
       print(f);
    }
   public static void print(File f){
       if(f!=null){
           if(f.isDirectory()){
                File[] fileArray=f.listFiles();
                if(fileArray!=null){
                    for (int i = 0; i <filearray.length; i++)="" {="" 递归调用="" print(filearray[i]);="" }="" else{="" system.out.println(f);="" }<="" pre="">
<p></p>
<h2>10.RandomAccessFile类</h2>
<p>该对象并不是流体系中的一员,其封装了字节流,同时还封装了一个缓冲区(字符数组),通过内部的指针来操作字符数组中的数据。该对象特点:</p>
<p>该对象只能操作文件,所以构造函数接收两种类型的参数:a.字符串文件路径;b.File对象。</p>
<p>该对象既可以对文件进行读操作,也能进行写操作,在进行对象实例化时可指定操作模式(r,rw)</p>
<p>注意:该对象在实例化时,如果要操作的文件不存在,会自动创建;如果文件存在,写数据未指定位置,会从头开始写,即覆盖原有的内容。可以用于多线程下载或多个线程同时写数据到文件。</p>
<p align="left">【案例】使用RandomAccessFile写入文件</p>
<p align="left"></p>
<pre class="brush:java;">/**
* 使用RandomAccessFile写入文件
* */
import java.io.*;
class hello{
    public static void main(String[]args) throws IOException {
        StringfileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        RandomAccessFile demo=newRandomAccessFile(f,"rw");
       demo.writeBytes("asdsad");
        demo.writeInt(12);
        demo.writeBoolean(true);
        demo.writeChar('A');
        demo.writeFloat(1.21f);
        demo.writeDouble(12.123);
        demo.close(); 
    }
}</pre>
<p></p>
<h1>Java IO流的高级概念</h1>
<h2>编码问题</h2>
<p>【案例 】取得本地的默认编码</p>
<p></p>
<pre class="brush:java;">/**
* 取得本地的默认编码
* */
publicclass CharSetDemo{
    public static void main(String[] args){
        System.out.println("系统默认编码为:"+ System.getProperty("file.encoding"));
    }
}</pre>
<p></p>
<p>【案例 】乱码的产生</p>
<p></p>
<pre class="brush:java;">import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
 
/**
* 乱码的产生
* */
public class CharSetDemo2{
    public static void main(String[] args) throws IOException{
        File file = new File("d:" + File.separator + "hello.txt");
        OutputStream out = new FileOutputStream(file);
        byte[] bytes = "你好".getBytes("ISO8859-1");
        out.write(bytes);
        out.close();
    }//输出结果为乱码,系统默认编码为GBK,而此处编码为ISO8859-1
}</pre>
<h2>对象的序列化</h2>
<p>对象序列化就是把一个对象变为二进制数据流的一种方法。</p>
<p>一个类要想被序列化,就行必须实现java.io.Serializable接口。虽然这个接口中没有任何方法,就如同之前的cloneable接口一样。实现了这个接口之后,就表示这个类具有被序列化的能力。先让我们实现一个具有序列化能力的类吧:</p>
<p>【案例 】实现具有序列化能力的类</p>
<p></p>
<pre class="brush:java;">import java.io.*;
/**
* 实现具有序列化能力的类
* */
public class SerializableDemo implements Serializable{
    public SerializableDemo(){
        
    }
    publicSerializableDemo(String name, int age){
        this.name=name;
        this.age=age;
    }
    @Override
    public String toString(){
        return "姓名:"+name+"  年龄:"+age;
    }
    private String name;
    private int age;
}</pre>
<p></p>
<p>【案例 】序列化一个对象 – ObjectOutputStream</p>
<p></p>
<pre class="brush:java;">import java.io.Serializable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* 实现具有序列化能力的类
* */
public class Person implements Serializable{
    public Person(){
     }
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString(){
        return "姓名:" +name + "  年龄:" +age;
    }
    private String name;
    private int age;
}
/**
* 示范ObjectOutputStream
* */
public class ObjectOutputStreamDemo{
    public static voidmain(String[] args) throws IOException{
        File file = newFile("d:" + File.separator + "hello.txt");
        ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream(
                file));
        oos.writeObject(newPerson("rollen", 20));
        oos.close();
    }
}</pre>
<p></p>
<p>【案例 】反序列化—ObjectInputStream</p>
<p></p>
<pre class="brush:java;">import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
 
/**
* ObjectInputStream示范
* */
public class ObjectInputStreamDemo{
    public static voidmain(String[] args) throws Exception{
        File file = new File("d:" +File.separator + "hello.txt");
        ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
                file));
        Object obj =input.readObject();
        input.close();
        System.out.println(obj);
    }
}</pre>
<p></p>
<p>注意:被Serializable接口声明的类的对象的属性都将被序列化,但是如果想自定义序列化的内容的时候,就需要实现Externalizable接口。</p>
<p>当一个类要使用Externalizable这个接口的时候,这个类中必须要有一个无参的构造函数,如果没有的话,在构造的时候会产生异常,这是因为在反序列话的时候会默认调用无参的构造函数。</p>
<p>现在我们来演示一下序列化和反序列话:</p>
<p>【案例 】使用Externalizable来定制序列化和反序列化操作</p>
<p></p>
<pre class="brush:java;">package IO;
 
import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
 
/**
* 序列化和反序列化的操作
* */
public class ExternalizableDemo{
    public static voidmain(String[] args) throws Exception{
        ser(); // 序列化
        dser(); // 反序列话
    }
 
    public static void ser()throws Exception{
        File file = newFile("d:" + File.separator + "hello.txt");
        ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(
                file));
        out.writeObject(newPerson("rollen", 20));
        out.close();
    }
 
    public static void dser()throws Exception{
        File file = newFile("d:" + File.separator + "hello.txt");
        ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
                file));
        Object obj =input.readObject();
        input.close();
       System.out.println(obj);
    }
}
 
class Person implements Externalizable{
    public Person(){
 
    }
 
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
 
    @Override
    public String toString(){
        return "姓名:" +name + "  年龄:" +age;
    }
 
    // 复写这个方法,根据需要可以保存的属性或者具体内容,在序列化的时候使用
    @Override
    public voidwriteExternal(ObjectOutput out) throws IOException{
       out.writeObject(this.name);
        out.writeInt(age);
    }
 
    // 复写这个方法,根据需要读取内容 反序列话的时候需要
    @Override
    public voidreadExternal(ObjectInput in) throws IOException,
           ClassNotFoundException{
        this.name = (String)in.readObject();
        this.age =in.readInt();
    }
 
    private String name;
    private int age;
}</pre>
<p></p>
<p>注意:Serializable接口实现的操作其实是吧一个对象中的全部属性进行序列化,当然也可以使用我们上使用是Externalizable接口以实现部分属性的序列化,但是这样的操作比较麻烦,</p>
<p>当我们使用Serializable接口实现序列化操作的时候,如果一个对象的某一个属性不想被序列化保存下来,那么我们可以使用transient关键字进行说明:</p>
<p>【案例 】使用transient关键字定制序列化和反序列化操作</p>
<p></p>
<pre class="brush:java;">package IO;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
/**
* 序列化和反序列化的操作
* */
public class serDemo{
    public static voidmain(String[] args) throws Exception{
        ser(); // 序列化
        dser(); // 反序列话
    }
 
    public static void ser()throws Exception{
        File file = newFile("d:" + File.separator + "hello.txt");
        ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(
                file));
        out.writeObject(newPerson1("rollen", 20));
        out.close();
    }
 
    public static void dser()throws Exception{
        File file = newFile("d:" + File.separator + "hello.txt");
        ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
                file));
        Object obj =input.readObject();
        input.close();
       System.out.println(obj);
    }
}
 
class Person1 implements Serializable{
    public Person1(){
 
    }
 
    public Person1(Stringname, int age){
        this.name = name;
        this.age = age;
    }
 
    @Override
    public String toString(){
        return "姓名:" +name + "  年龄:" +age;
    }
 
    // 注意这里
    private transient Stringname;
    private int age;
}</pre>
<p></p>
<p>【运行结果】:</p>
<p>姓名:null  年龄:20</p>
<p>【案例 】序列化一组对象</p>
<p></p>
<pre class="brush:java;">import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
public class SerDemo1{
    public static voidmain(String[] args) throws Exception{
        Student[] stu = { newStudent("hello", 20), new Student("world", 30),
                newStudent("rollen", 40) };
        ser(stu);
        Object[] obj = dser();
        for(int i = 0; i <obj.length; ++i){="" student="" s="(Student)" obj[i];="" system.out.println(s);="" }="" 序列化="" public="" static="" voidser(object[]="" obj)="" throws="" exception{="" file="" +="" file.separator="" "hello.txt");="" objectoutputstream="" out="new" objectoutputstream(new="" fileoutputstream(="" file));="" out.writeobject(obj);="" out.close();="" 反序列化="" object[]dser()="" objectinputstreaminput="new" objectinputstream(new="" fileinputstream(="" object[]="" obj="(Object[])" input.readobject();="" input.close();="" return="" obj;="" class="" implements="" serializable{="" student(){="" student(stringname,="" int="" age){="" this.name="name;" this.age="age;" @override="" string="" tostring(){="" "姓名:="" "="" name="" 年龄:"="" age;="" private="" name;="" }<="" pre="">

猜你喜欢

转载自chengjiachen.iteye.com/blog/2250956