IO字节流

  

  

 

 

四部分:文件类型名:扩展名长度和内容   文件长度和内容

package Archive;

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

public class Archiver {
    /**
     * 创建归档文件
     * 
     * @throws Exception
     */

    public void newArchiveFile(String[] srcPaths, String yarPath) {
        FileOutputStream fout = null;
        try {
            // 创建yar归档文件的输出流
            fout = new FileOutputStream(yarPath);
            for (String srcPath : srcPaths) {
                // 向yar归档文件中添加文件
                addFile(srcPath, fout);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fout != null) {
                    fout.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 向yar归档文件中添加文件
     * 
     * @param srcPath
     * @param fout
     * @throws Exception
     */
    private void addFile(String srcPath, FileOutputStream fout) {
        FileInputStream fin=null;
        try{
            // 1.取出srcPath文件的类型
            int fType = getFileType(srcPath);
            
            // 2.取出文件的长度
            fin = new FileInputStream(srcPath);
            int length = fin.available();
            
            // 将ftype写入fout
            byte bFtype = (byte) fType;
            fout.write(new byte[] { bFtype });
            
            // 4.将长度写入yar中
            byte[] bytes = IntoByteArry(length);
            fout.write(bytes);
            
            // 5.写入文件的内容
            int len = -1;
            byte[] buffer = new byte[1024];
            while ((len = fin.read(buffer)) != -1) {
                fout.write(buffer, 0, len);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (fin != null) {
                    fin.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 将正数变成字节数组
     * 
     * @param length
     * @return
     */
    private byte[] IntoByteArry(int i) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) i;
        bytes[1] = (byte) (i >> 8);
        bytes[2] = (byte) (i >> 16);
        bytes[3] = (byte) (i >> 24);
        return bytes;

    }

    /**
     * 得到文件类型 
     * 0-txt 
     * 1-jpg 
     * 2-avi 
     * 3-gif 
     * 3-exe
     * 
     * @param srcPath
     * @return
     */
    private int getFileType(String srcPath) {
        // 得到扩展文件名
        String ext = srcPath.substring(srcPath.lastIndexOf(".")).toLowerCase();
        int type = -1;
        if (".txt".equals(ext)) {
            type = 0;
        } else if (".jpg".equals(ext)) {
            type = 1;
        } else if (".avi".equals(ext)) {
            type = 2;
        } else if (".gif".equals(ext)) {
            type = 3;
        } else if (".exe".equals(ext)) {
            type = 4;
        }else if(".jpeg".equals(ext)) {
            type=5;
        }else if(".yar".equals(ext)) {
            type=6;
        }
        return type;
    }
    
    /**
     * 添加文件到yar归档文件中
     */
    public void addFile(String srcPath,String yarPath) {
        try {
            FileOutputStream fos=new FileOutputStream(yarPath,true);
            addFile(srcPath,fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 解档文件
     */
    public void unarchive(String yarPath,String destDir) {
        FileInputStream fin=null;
        try {
            fin=new FileInputStream(yarPath);
            int i=1;
            //循环读取下一个文件
            while(readNextFile(destDir,(i++)+"",fin)) {
                
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            try {
                fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 读取下一个文件
     * @param fin
     * @return
     */
    private boolean readNextFile(String destDir,String fname,FileInputStream fin) {
        FileOutputStream fout=null;
        try {
            //文件类型
            int type=fin.read();
            //文件扩展名
            String ext = getFileTypeExt(type);
            if(type==-1) {
                return false;
            }
            /**
             * 开始读取文件并写入到新文件中
             */
            //0.构造文件
            fout=new FileOutputStream(destDir+"/"+fname+ext);
            //1.读取文件长度
            byte[] bytes=new byte[4];
            fin.read(bytes);
            
            //2.转换成字节数组成为int
            int fileLength=byteArryInt(bytes);
            
            //读取文件
            byte[] buffer=new byte[1024];
            
            //计算读取文件的循环次数
            int count=0;
            if(fileLength%buffer.length==0) {
                count=fileLength/buffer.length;
            }else {
                count=fileLength/buffer.length+1;
            }
            //开始循环读取
            for(int i=0;i<count;i++) {
                //不是最后一次
                if(i!=(count-1)) {
                    fin.read(buffer);
                    fout.write(buffer);
                }else {
                    byte[] buf0=new byte[fileLength%buffer.length];
                    fin.read(buf0);
                    fout.write(buf0);
                }
            }
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        finally {
//            try {
//                fout.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        return true;
    }
    private String getFileTypeExt(int type) {
        String ext=".TMP";
        switch(type) {
        case 0:
            ext=".txt";
            break;
        case 1:
            ext=".jpg";
            break;
        case 2:
            ext=".avi";
            break;
        case 3:
            ext=".gif";
            break;
        case 4:
            ext=".exe";
            break;
        case 5:
            ext=".jpeg";
            break;
        case 6:
            ext=".yar";
            break;
            default:
                ext=".tmp";
        }
        
        return ext;
    }

    /**
     * 将程度为4的字节数组转换成为int
     * @param bytes
     * @return
     */
    private int byteArryInt(byte[] bytes) {
        int i0=bytes[3]<<24;
        int i1=(bytes[2] & 0xff)<<16;
        int i2=(bytes[1] & 0xff)<<8;
        int i3=(bytes[0] & 0xff);
        return i0 | i1 | i2 | i3;
    }
}
package Archive;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.junit.jupiter.api.Test;

public class App {
    /**
     * 新建归档文件
     */
    @Test
    public void newArchiveFile() {
        Archiver archiver=new Archiver();
        String[] srcPaths= {
                "d:\arch\1.txt",
                "d:\arch\1.jpeg",
                "d:\arch\2.jpeg",
                "d:\arch\myyar.yar"
        };
        String yarPath="d:/arch/newyar.yar";
        archiver.newArchiveFile(srcPaths, yarPath);
        System.out.println("over!");
    }
    
    /**
     * 向原有归档文件中添加新文件
     */
    @Test
    public void addFile() {
        Archiver archiver=new Archiver();
        archiver.addFile("d:\arch\2.jpeg", "d:/arch/myyar.yar");
        System.out.println("over!");
    }
    /**
     *解档文件
     */
    @Test
    public void unarchiveFile() {
        Archiver archiver=new Archiver();
        archiver.unarchive("d:/arch/newyar.yar", "d:/arch/unarch");
        System.out.println("over!");
    }
    /**
     * 使用文本文件存储
     * @throws Exception 
     */
    @Test
    public void readMp3() throws Exception {
        FileOutputStream fos = new FileOutputStream("d:/arch/4.txt");
        FileInputStream fis = new FileInputStream("d:/arch/1.jpeg");
        int b = -1;
        while ((b = fis.read()) != -1) {
            fos.write((b + "").getBytes());
            fos.write(new byte[] { '	', '
' });
            ;
        }
        fos.close();
        fis.close();
    }
    /**
     * 使用文本文件存储
     * @throws Exception 
     */
    @Test
    public void readMp32() throws Exception {
        FileWriter writer = new FileWriter("d:/arch/4.txt");
        FileInputStream fis = new FileInputStream("d:/arch/1.jpeg");
        int len=-1;
        byte[] buffer=new byte[1024];
        while ((len = fis.read(buffer)) != -1) {
            writeByteArrTofile(buffer,0,len, writer);
        }
        writer.close();
        fis.close();
    }
    /**
     * 将字节数组中的字节数写入到fos中
     * 
     */
    private void writeByteArrTofile(byte[] arr,int startIndex,int length,FileWriter writer) {
        
        try {
            for(int j=startIndex;j<length;j++) {
                writer.write(arr[j]+"
");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 读取文本文件的内容,写入到jpeg文件中,恢复图像数据
     */
    @Test
    public void reaTxt2JPEG() {
        try {
            BufferedReader reader=new BufferedReader(new FileReader("d:/arch/4.txt"));
            FileOutputStream fos=new FileOutputStream("d:/arch/1.jpeg");
            String line=null;
            //循环读行
            while((line=reader.readLine())!=null) {
                //把每行数字变换成byte
                //byte b=(byte)Integer.parseInt(line);
                fos.write(Integer.parseInt(line));
            }
            fos.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
package base;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import org.junit.jupiter.api.Test;

public class ByteStreamDemo {
    /**
     * 使用字节流复制图片
     * @throws IOException 
     */
    @Test
    public     void copyImage() throws IOException {
        //文件输入流(字节流)
        FileInputStream fin = new FileInputStream("D:\1.jpeg");
        //输出流
        FileOutputStream fout = new FileOutputStream("D:\2.jpeg",false);
        
        fin.available();//文件长度字节数
        byte[] buffer=new byte[1024];
        int len=-1;
        while(((len=fin.read(buffer))!=-1)) {
            fout.write(buffer,0,len);
        }
        fin.close();
        fout.close();
    }
    
    /**
     * 使用文件输出流写文本文件
     * @throws Exception 
     */
    @Test
    public void writeFileWithFileOutputStream() throws Exception {
        System.out.println(Charset.defaultCharset());
        String str="你好,中国人!hello world.";
        FileOutputStream fos=new FileOutputStream("D:\1.txt");
        fos.write(str.getBytes("utf-8"));
        fos.close();
        System.out.println("over");
    }
    
    /**
     * 使用文件输入流读取文件
     * @throws Exception 
     */
    
    @Test
    public void readFileWithFileInputStream() throws Exception {
        FileInputStream fis = new FileInputStream("d:\1.txt");
        char c=(char)fis.read();
        System.out.println(c);
    }
    
    /**
     * 跳过字节
     * 负数-前跳,正数后跳
     * @throws Exception 
     */
    @Test
    public void skipByteTest() throws Exception {
        FileInputStream fis=new FileInputStream("d:1.txt");
        int c=-1;
        while((c=fis.read())!=-1) {
            fis.skip(1);
            System.out.println((char)c);
        }
    }
}
package Archive;

import java.io.FileOutputStream;
import java.io.RandomAccessFile;

import org.junit.jupiter.api.Test;

/**
 * 随机访问文件
 * @author ASUS
 *
 */
public class RandomAccessFileDemo {
    public static void main(String[] args) throws Exception {
        RandomAccessFile raf=new RandomAccessFile("d:/arch/9.txt", "rwd");
        raf.write("hello world".getBytes());
        
        //定位文件
        raf.seek(3);
        int c=-1;
        while((c=raf.read())!=-1) {
            System.out.print((char)c);
        }
        raf.close();
        System.out.println("over");
    }
    
    /**
     * 文件内容重复
     * @throws Exception 
     */
    @Test
    public void duplicateFile() throws Exception {
        RandomAccessFile raf = new RandomAccessFile("D:\arch\5.txt","rw");
        FileOutputStream fos=new FileOutputStream("d:/arch/6.txt")    ;
        byte[] buffer=new byte[1024];
        int len=-1;
        
        while((len=raf.read(buffer))!=-1) {
            fos.write(buffer,0,len);
            
        }
        raf.seek(0);
        while((len=raf.read(buffer))!=-1) {
            fos.write(buffer,0,len);
            
        }
        raf.seek(0);
        while((len=raf.read(buffer))!=-1) {
            fos.write(buffer,0,len);
            
        }
        fos.close();
        raf.close();
    }
}
package Archive;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

import org.junit.jupiter.api.Test;

public class PrintStreamDemo {
    /**
     * 改变系统的out输出流向
     * 默认是console
     * @throws Exception 
     */
    @Test
    public void sysoutTest() throws Exception {
        PrintStream ps =new PrintStream(new FileOutputStream("d:/arch/log.log"));
        //改变系统输出流向
        System.setOut(ps);
        System.out.println("hello world");
    }
    /**
     * 从控制台读取输入字符,打印在控制台上
     * @throws Exception 
     */
    @Test
    public void systemin() throws Exception {
        //改变系统输入流向
        System.setIn(new FileInputStream("d:/arch/1.txt"));
         BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
         while(true) {
             String line=reader.readLine();
             if("exit".equals(line)) {
                 System.exit(-1);
             }
             System.out.println(line);
         }
    }
}
package Archive;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.junit.jupiter.api.Test;

/**
 * 使用转换流,桥梁(字节-->字符)
 * @author ASUS
 *
 */
public class InputStreamReaderDemo {
    
    /**
     * 使用转换流读取文本
     * @throws Exception
     */
    @Test
    public void read() throws Exception{
        InputStreamReader reader = new InputStreamReader(new FileInputStream("D:\arch\4.txt"),"gbk");
        char[] buffer=new char[1024];
        int len=-1;
        while((len=reader.read(buffer))!=-1) {
            System.out.println(new String(buffer,0,len));;
        }
        reader.close();
    }
    /**
     * 通过字节流读取文本文件的内容,观察字符数组的范围
     * @throws Exception
     */
    @Test
    public void readInByte() throws Exception{
        FileInputStream fin = new FileInputStream("D:\arch\4.txt");
        byte[] buffer=new byte[1024];
        int len=-1;
        while((len=fin.read(buffer))!=-1) {
            System.out.println(new String(buffer,0,len));;
        }
        fin.close();
    }
    /**
     * 考查System.out类
     */
    public void sysoutTest() {
        System.out.print("jfdl");
    }
}
package Archive;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

import org.junit.jupiter.api.Test;

public class BufferedInputStreamDemo {
    
    /**
     * 使用缓冲区字节流读取文件
     * @throws Exception
     */
    @Test
    public void bufferedInputStreamTest() throws Exception {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("D:\arch\4.txt"));
        int i=-1;
        while((i=in.read())!=-1) {
            System.out.println(i);
        }
        in.close();
    }
}
原文地址:https://www.cnblogs.com/King-boy/p/11037570.html