Java IO流

IO流

1. FileInputStream/FileOutputStream

public class FileInputStreamTest {

    public static void main(String[] args) throws IOException {
        //创建字节输入流
        FileInputStream fis = new FileInputStream("E:\\20160928JavaBase\\Test\\aaa\\qqq.txt");
        //创建一个长度为1024的“竹筒”
        byte[] bbuf = new byte[1024];
        //用于保存实际读取的字节数
        int hasRead = 0;
        //使用循环来重复“取水”的过程
        while((hasRead = fis.read(bbuf)) > 0){
            //取出“竹筒”中的水滴(字节),将字节数组转换成字符串输入!
            System.out.print(new String(bbuf,0,hasRead));
        }
        fis.close();
    }
public class FileOutputStreamTest {

    public static void main(String[] args) throws IOException{
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("E:\\20160928JavaBase\\Test\\aaa\\qqq.txt");
            fos = new FileOutputStream("E:\\20160928JavaBase\\Test\\bbb\\qqq.txt");

            byte[] bbuf = new byte[32];
            int hasRead = 0;
            while((hasRead = fis.read(bbuf))>0){
                //每读取一次,即写入文件输出流,读了多少,就写了多少
                fos.write(bbuf, 0, hasRead);
            }

        }finally{
            if(fis != null){
                fis.close();
            }
            if(fos != null){
                fos.close();
            }
        }
    }
}
public static void main(String[] args) throws IOException{

        FileInputStream in = null;
        FileOutputStream out = null;
        String fatherPath = "E:\\20160928JavaBase\\Test\\";
        //来源文件:读取内容
        in = new FileInputStream(fatherPath+"aaa\\qqq.txt");
        //目标文件:写入内容
        out = new FileOutputStream(fatherPath+"bbb\\qqq.txt");
        //按字节读取
        byte[] bytearray = new byte[1024];
        try {
            do{
                in.read(bytearray,0,1024);
                out.write(bytearray);
            }while(in.available() > 0);
            System.out.println("执行完毕!");
        } finally{
            if(in != null){
                in.close();
            }
            if(out != null){
                out.close();
            }
        }

2. FileReader/FileWriter

public class FileReaderTest {

    public static void main(String[] args) throws IOException {
        FileReader fr = null;
        try {
            fr = new FileReader("E:\\20160928JavaBase\\Test\\aaa\\qqq.txt");
            char[] cbuf = new char[32];
            int hasRead = 0;
            while((hasRead = fr.read(cbuf))>0){
                System.out.print(new String(cbuf, 0, hasRead));
            }
        }finally{
            if(fr != null){
                fr.close();
            }

        }
    }
}
public class FileWriterTest {

    public static void main(String[] args) throws IOException{

        FileWriter fw = null;
        try {
            fw = new FileWriter("E:\\20160928JavaBase\\Test\\aaa\\qqqq.txt");
            fw.write("你好!\r\n");
            fw.write("你dsc好!\r\n");
            fw.write("你好ererer!\r\n");
            fw.write("你好erererer!\r\n");
            fw.write("你好ererererere!\r\n");
        } finally{
            if(fw != null){
                fw.close();
            }

        }
    }
}

3. PrintStream

public class PrintStreamTest {

    public static void main(String[] args) throws IOException {

        PrintStream ps = null;
        try {
            //创建一个节点输出流:FileOutStream
            FileOutputStream fos = new FileOutputStream("E:\\20160928JavaBase\\Test\\aaa\\test.txt");
            //以PrintStream 来包装 FileOutputStream
            ps = new PrintStream(fos);
            //使用PrintStream执行输出
            ps.println("普通字符串");
            //直接使用PrintStream输出对象
            ps.println(new PrintStreamTest());

        }finally{
            ps.close();
        }
    }
}
package com.hz.practice;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
 * 处理流:输出很强势
 * @author ztw
 *
 */
public class Test03 {

    public static void main(String[] args) throws IOException {

        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream("E:\\20160928JavaBase\\Test\\aaa\\eee.txt");
            ps = new PrintStream(fos);
            ps.println("普通字符串");
            ps.println(new Test03());
        } finally{
            ps.close();
        }

    }
}

3. RandomAccessFile

public class RandomAccessFileTest {

    public static void main(String[] args) {

        File file = new File("E:\\20160928JavaBase\\Test01\\gg\\bbb.txt");
        try {
            randomAccessFile(file);
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public static void randomAccessFile(File file) throws IOException {

        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "rw");//"rw"读写权限
            System.out.println("文件指针的位置,初始位置为0:"+raf.getFilePointer());
            //指针移动到什么位置
            raf.seek(5);
            byte[] bbuf = new byte[1024];

            int hasRead = 0;

            while((hasRead = raf.read(bbuf))>0){

                System.out.println(new String(bbuf,0,hasRead));
            }
            raf.seek(raf.length());
            raf.write("你好我的世界".getBytes());

        } finally{
            if(raf != null){
                raf.close();
            }

        }
    }
}
public class InsertContent {

    public static void main(String[] args) {
        try {
            insert("E:\\20160928JavaBase\\Test01\\gg\\bbb.txt", 5, "世界你好");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void insert(String file,long pos,String content) throws IOException {

        RandomAccessFile raf = null;
        //定义一个临时存储文件
        File tmp = File.createTempFile("tmp", null);
        FileInputStream tmpFis = null;
        FileOutputStream tmpFos = null;
        //当JVM结束就自动删除文件
        tmp.deleteOnExit();
        try {
            raf = new RandomAccessFile(file, "rw");
            tmpFis = new FileInputStream(tmp);
            tmpFos = new FileOutputStream(tmp);
            //获取要插入的指针位置
            raf.seek(pos);
            byte[] bbuf = new byte[63];
            int hasRead = 0;
            while((hasRead = raf.read(bbuf)) > 0 ){
                tmpFos.write(bbuf, 0, hasRead);
            }
            //插入内容
            //又获取到要插入的指针位置
            raf.seek(pos);
            //追加内容
            raf.write(content.getBytes());
            while((hasRead = tmpFis.read(bbuf)) > 0){
                raf.write(bbuf, 0, hasRead);
            }
        } finally{
                raf.close();

        }

    }
}

4. InputStreamReader

package com.hz.practice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class KeyinTest {

    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            //将System.in对象转换成Reader对象
            InputStreamReader reader = new InputStreamReader(System.in);
            //将普通的Reader包装成BufferedReader
            br = new BufferedReader(reader);
            String buffer = null;
            //采用循环方式来一行一行的读取
            while((buffer = br.readLine()) != null){
                //如果读取的字符串为“exit”,程序退出
                if(buffer.equals("exit")){
                    System.exit(1);
                }
                //打印读取内容
                System.out.println("输入内容为:" + buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

5. InputStreamReader

package com.hz.practice;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Java虚拟机读写其他进程的数据
 * @author ztw
 *
 */
public class ReadFromProcess {

    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            //运行javac命令,返回运行该命令的子进程
            Process p = Runtime.getRuntime().exec("javac ReadFromProcess.java");
            br = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            String buffer = null;
            while((buffer = br.readLine())!= null){
                System.out.println(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(br != null){
                    br.close();
                }

            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
    }
}

6. ObjectOutputStream/ObjectInputStream

package com.hz.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Person implements Serializable{//Serializable序列化

    private String name;
    private int age;
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {

        out.writeObject(new StringBuffer(name).reverse());
        out.writeInt(age);

    }

    private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException {

        this.name = ((StringBuffer)in.readObject()).reverse().toString();
        this.age = in.readInt();
    }

}
package com.hz.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class PersonSerialible {

    public static void main(String[] args) {

        ObjectOutputStream fos = null;
        ObjectInputStream fis = null;
        try {
            fos = new ObjectOutputStream(new FileOutputStream("test.txt"));
            Person p = new Person("张三", 15);
            fos.writeObject(p);
            fis = new ObjectInputStream(new FileInputStream("test.txt"));
            Person p2 = (Person) fis.readObject();
            System.out.println(p2.getName()+p2.getAge());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally{
            if(fos != null){
                try {
                    fos.close();
                    fos = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                    fis = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

7. FileChannel(新版本后的流)

public class FileChannelTest {

    public static void main(String[] args) {

        FileChannel inChannel = null;
        FileChannel outChannel = null;

        try {
            File f = new File("E:\\20160928JavaBase\\Test\\ccc\\FileChannelTest.txt");
            inChannel = new FileInputStream(f).getChannel();
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
            Charset charset = Charset.forName("GBK");
            outChannel = new FileOutputStream("a.txt").getChannel();
            //直接将buffer里的数据全部输出
            outChannel.write(buffer);
            buffer.clear();
            //创建解码器(CharsetDecoder)对象
            CharsetDecoder decoder = charset.newDecoder();
            //使用解码器将ByteBuffer转换成CharBuffer
            CharBuffer charBuffer = decoder.decode(buffer);
            //CharBuffer的toString方法可以获取对应的字符串
            System.out.println(charBuffer);



        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(inChannel !=null){
                    inChannel.close();
                }
                if(outChannel != null){
                    outChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
package com.hz.test;

import java.nio.charset.Charset;
import java.util.Properties;
import java.util.SortedMap;

/**
 * 获取JDK所支持的全部字符
 * @author ztw
 *
 */
public class CharsetTest {

    public static void main(String[] args) {
        SortedMap<String,Charset> map = Charset.availableCharsets();
        for (String alias : map.keySet()) {
            System.out.println(alias + "------>"+map.get(alias));
        }
        Properties name = System.getProperties();
        System.out.println(name);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值