【JAVASE(1)】JAVASE文件操作案例篇

一、关于文件操作的案例实现:

实现文件的复制实例一:

public void copyFileWithBuffered(String srcPath,String desPath){
        BufferedInputStream bis=null;
        BufferedOutputStream bos =null;
        try{
            
            File srcfile = new File(srcPath);
            File desfile = new File(desPath);

            FileInputStream fis=new FileInputStream(srcfile);
            FileOutputStream fos=new FileOutputStream(desfile);

            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            byte[] buffer = new byte[5];
            int len=0;
            while ((len=bis.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
        }catch (IOException e){e.printStackTrace();}finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
}

实现文件的复制实例二:

    @Test
    public void  testBufferedReaderBufferedWriter(){
        BufferedReader br=null;
        BufferedWriter bw =null;
        try {
            br = new BufferedReader(new FileReader(new File(
                    "全路径\\源文本文件"
            )));

            bw = new BufferedWriter(new FileWriter(new File(
                    "全路径\\目标文本文件"
            )));

            //方式一:使用char型数组
            //char[] cbuf = new char[5];
            //nt len=0;
            //while ((len=br.read(cbuf))!=-1){
            //  bw.write(cbuf,0,len);
            //}

            //方式二:使用String
            String data=null;
            while ((data=br.readLine())!=null){
                //方法一
                //bw.write(data);
                //方法二
                bw.write(data);
                bw.newLine();//提供换行操作
            }


        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

实现文件的复制实例三:

    @Test
    public void testFileWriterFileReader00(){

        FileReader fr=null;
        FileWriter fw=null;
        try {
            //1、File类的实例化两个,一个是读入对象,一个是写出对象
            File srcFile = new File(
                    srcPath
            );
            File desFile = new File(
                   desPath
            );
            fr =new FileReader(srcFile);
            fw=new FileWriter(desFile);
            char[] cbuf=new char[5];
            int len=0;
            while ((len=fr.read(cbuf))!=-1){
                String str = new String(cbuf, 0, len);
                fw.write(str);
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

实现指定路径下的文件复制

public void copyFile(String srcPath,String desPath){
        FileInputStream fis=null;
        FileOutputStream fos=null;
        try{
            //File类的实例化
            File srcfile = new File(srcPath);

            File desfile = new File(desPath);

            fis = new FileInputStream(srcfile);
            fos = new FileOutputStream(desfile);

            byte[] bbuf = new byte[5];
            int len=0;
            while ((len=fis.read(bbuf))!=-1){
                fos.write(bbuf,0,len);
            }

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

            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
}

对图片加密解密小案例:

    @Test
    public void test00(){//对图片加密
        FileInputStream fis=null;
        FileOutputStream fos=null;

        try {
            fis = new FileInputStream(
                "全路径\\目标待复制图片"
            );
            fos=new FileOutputStream(
                "全路径\\目标已加密复制图片"
            );
            byte[] buffer = new byte[20];
            int len;
            while ((len=fis.read(buffer))!=-1){
                //字节数据进行修改
                for (int i = 0; i < len; i++) {
                    buffer[i]=(byte) (buffer[i]^5);
                }

                fos.write(buffer,0,len);
            }


        }catch (IOException e){e.printStackTrace();}finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //tip:对于与操作有: m=5;n=12;m^n^n=m

    @Test
    public void test01(){//对图片解密
        FileInputStream fis=null;
        FileOutputStream fos=null;

        try {
            fis = new FileInputStream(
                    "全路径\\目标已加密复制图片"
            );
            fos=new FileOutputStream(
                    "全路径\\目标已解密复制图片"
            );
            byte[] buffer = new byte[20];
            int len;
            while ((len=fis.read(buffer))!=-1){
                //字节数据进行修改
                for (int i = 0; i < len; i++) {
                    buffer[i]=(byte) (buffer[i]^5);
                }

                fos.write(buffer,0,len);
            }


        }catch (IOException e){e.printStackTrace();}finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

统计文本中字符个数:

    @Test
    public void test02(){
        FileReader fr=null;
        BufferedWriter bw=null;
        try {
            HashMap<Character, Integer> map = new HashMap<>();

            fr=new FileReader(
                "全路径\\目标文本"
            );
            int c=0;
            while ((c=fr.read())!=-1){
                char ch=(char) c;
                if(map.get(ch)==null){
                    map.put(ch,1);
                }else {
                    map.put(ch,map.get(ch)+1);
                }
            }

            bw=new BufferedWriter(new FileWriter(
                    "全路径\\统计结果文本"
            ));

            Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
            for (Map.Entry<Character, Integer> entry : entrySet) {
                switch (entry.getKey()){
                    case ' ':
                       bw.write("空格="+entry.getValue());
                       break;
                    case '\t':
                        bw.write("tab键="+entry.getValue());
                        break;
                    case '\r':
                        bw.write("回车="+entry.getValue());
                        break;
                    case '\n':
                        bw.write("换行="+entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey()+"="+entry.getValue());
                        break;
                }
                bw.newLine();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

综合使用InputStreamReader和OutputStreamWriter:

    @Test
    public void test01(){//综合使用InputStreamReader和OutputStreamWriter
        FileInputStream fis =null;
        FileOutputStream fos=null;
        InputStreamReader isr=null;
        OutputStreamWriter osw=null;


        try{
            File srcFile = new File(
                    "全路径\\目标文本"
            );

            File desFile = new File(
                    "全路径\\结果文本"
            );

            fis = new FileInputStream(srcFile);
            fos=new FileOutputStream(desFile);

            isr=new InputStreamReader(fis,"UTF-8");
            osw=new OutputStreamWriter(fos,"GBK");

            //读写过程
            char[] cbuf = new char[6];
            int len=0;
            while ((len=isr.read(cbuf))!=-1){
                osw.write(cbuf,0,len);
            }

        }catch (IOException e){e.printStackTrace();}finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

序列化和反序列化:

    @Test
    public void testObjectInputStream00(){//反序列化
        ObjectInputStream ois =null;
        try {
            ois = new ObjectInputStream(new FileInputStream(
                "全路径\\目标文件"
            ));
            Object obj = ois.readObject();
            String str=(String)obj;
            System.out.println(str);


        }catch (IOException e){
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void testObjectOutputStream00(){//序列化过程
        ObjectOutputStream oos =null;
        try {
            oos=new ObjectOutputStream(new FileOutputStream(
                    "全路径\\目标文件"
            ));
            oos.writeObject(new String("文件中要书写的内容"));
            oos.flush();


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

使用RandomAccessFile实现对原有文本文件中内容进行插入操作:

    @Test
    public void test02(){//使用RandomAccessFile实现对原有文本文件中内容进行插入操作
        RandomAccessFile rafOne=null;
        try{
            rafOne=new RandomAccessFile(
                    new File("全路径\\目标文本"),
                    "rw"
            );
            rafOne.seek(3);//将指针调到3的位置
            //保存指针3后面的所有数据到StringBuilder中
            StringBuilder builder = new StringBuilder(
                (int) new File("全路径\\目标文本").length()
            );
            byte[] buffer = new byte[20];
            int len=0;
            while ((len=rafOne.read(buffer))!=-1){
                builder.append(new String(buffer,0,len));
            }
            rafOne.seek(10);//回调指针
            rafOne.write("XYZ".getBytes());//写插入数据

            //将StringBuilder中数据回写
            rafOne.write(builder.toString().getBytes());


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

    }

定义一个方法,参数传递File类型目录,方法中对目录进行遍历:

public static void getAllFile(File dir){
        System.out.println(dir);
        File[] files = dir.listFiles();
        for (File f : files) {
          if(f.isDirectory()){
              getAllFile(f);
          }else{
              System.out.println(f);
          }
        }
}

​​

二、详解文件上传代码实现:
客户端

public class TCPUpClient {
    public static void main(String[] args) throws IOException {
        function();
    }

    private static void function() throws IOException {
        //1.创建一个本地字节输入流FileInputStream对象,构造方法中绑定要读取的数据源
        FileInputStream fis = new FileInputStream("全路径\\上传目标文件");

        //2.创建客户端Socket对象,构造方法中绑定服务器的ip地址和端口号
        Socket socket = new Socket("IP地址", 端口号1);

        // 3.使用Socket中的方法getOutputStream获取网络字节输出流OutputStream对象
        OutputStream os = socket.getOutputStream();

        //4.使用本地字节输入流对象FileInputStream对象中的方法read读取文件
        int len=0;
        byte[] bytes=new byte[1024];
        while ((len=fis.read(bytes))!=-1){
            //5.使用网络字节输出流OutputStream对象中的方法write把读取到的文件上传到服务器
            os.write(bytes,0,len);
        }

        /*
            上传完给服务器写一个结束标记
            void shutdownOutput()禁用此套接字的输出流
            对应TCP套接字,任何以前写入的数据都将被发送,并且后跟随TCP的正常终止序列
         */
        socket.shutdownOutput();

        // 6.使用Socket中的方法getInputStream获取网络字节输出流InputStream对象
        InputStream is = socket.getInputStream();

        //7.使用网络字节输入流InputStream对象中的方法read读取服务器回写的数据
        while ((len=is.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }

        //8.释放资源(FileInputStream,Socket)
        fis.close();
        socket.close();
    }
}

服务器端:

public class TCPUpServer {
    public static void main(String[] args) throws IOException {
        function();
    }

    private static void function() throws IOException {
        //1.创建一个服务器ServerSocket对象,和系统要指定的端口号
        ServerSocket server = new ServerSocket(端口号1);

        //2.使用ServerSocket对象中的方法accept获取到请求的客户端Socket对象
        /*
            让服务器一直处于监听状态(死循环accept)
            有一个客户端上传文件,就保存一个文件
         */

        while (true) {
            Socket socket = server.accept();
            /*
                采用多线程技术提高程序的效率
                有一个客户端上传文件,就开启一个线程,完成文件的上传
             */

            new Thread(new Runnable() {
                //上传文件
                @Override
                public void run() {
                    try {
                        //3.使用Socket对象中方法getInputStream获取到网络字节输入流InputStream对象
                        InputStream is = socket.getInputStream();
                        //4.判断目标路径中指定文件夹是否存在
                        File file = new File("全路径\\指定文件夹");
                        if (!file.exists()) {
                            file.mkdir();

                        }
                        /*
                            自定义一个文件的命名规则:防止同名文件被覆盖
                            规则:域名+毫秒值+随机数
                        */
                        String fileName = "OneDay" + System.currentTimeMillis() + new Random().nextInt(999999) + ".txt";

                        //5.创建一个本地字节输出流FileOutputStream对象,构造方法中要绑定输出的目的地
                        //FileOutputStream fos = new FileOutputStream(file + "\\new_name.txt");
                        FileOutputStream fos = new FileOutputStream(file + "\\" + fileName);

                        //6.使用网络字节输出流InputStream对象中的方法read读取客户端上传的文件
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while ((len = is.read(bytes)) != -1) {
                            //7.使用本地字节输出流FileOutputStream对象中的方法write把读取到的文件保存到服务器的硬盘上
                            fos.write(bytes, 0, len);
                        }
                        //8.使用Socket对象中的方法getOutputStream对象
                        //9.使用网络字节输出流OutputStream中的方法write,给客户端回写:上传成功
                        socket.getOutputStream().write("上传成功".getBytes());
                        //10.释放资源:FileOutputStream,Socket,ServerSocket
                        fos.close();
                        socket.close();
                    }catch (IOException e){
                        System.out.println(e);
                    }
                }
            }).start();
        }
        //服务器不用关闭
        //server.close();
    }
}

以上是今日小节,不喜勿喷,感谢理解。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值