博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IO字节流
阅读量:4619 次
发布时间:2019-06-09

本文共 12927 字,大约阅读时间需要 43 分钟。

  

 

  

 

 

 

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

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
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[] { '\t', '\n' });            ;        }        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

 

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

你可能感兴趣的文章
【codecombat】 试玩全攻略 第一关kithguard地牢
查看>>
【DP】 POJ 1191 棋盘分割 记忆化搜索
查看>>
自动化测试 Appium之Python运行环境搭建 Part2
查看>>
说说DBA职责和目标
查看>>
从头认识Spring-2.4 基于java的标准注解装配-@Inject-限定器@Named
查看>>
sql server 实现多表连接查询
查看>>
Python标准库:内置函数getattr(object, name[, default])
查看>>
转:android 自定义RadioButton样式
查看>>
HTTP请求过程
查看>>
织梦多域名解析到同一个空间导致打开链接不一致怎么办?
查看>>
Xcode10 library not found for -lstdc++ 找不到问题
查看>>
Mysql 8.0.13如何重置密码
查看>>
发布功能完成
查看>>
excel 合并单元格
查看>>
iOS设计模式简介
查看>>
c# 扩展方法 奇思妙用 高级篇 九:OrderBy(string propertyName, bool desc)
查看>>
C语言中的地址传递(传指针,传递给形参的指针仍然是实参指针的一份拷贝)
查看>>
redis缓存数据库及Python操作redis
查看>>
opencms忘记Admin用户登录密码解决方案
查看>>
forms组件
查看>>