Java多线程写文件

问题场景

调用多个线程将多个文件进行合并,当初没有考虑到多线程操作文件会造成的脏数据,导致了业务出问题。

解决方法

审查文件操作的方法,进行文件加锁,同一时间只能一个线程对文件进行操作。

代码展示

public static void copyFile(String srcFilePath, String destFilePath)
            throws IOException {
        FileInputStream in = null;
        FileOutputStream out = null;
        FileLock flout = null;
        FileChannel fcIn = null;
        FileChannel fcOut = null;
        try { // 获取源文件和目标文件的输入输出流
            in = new FileInputStream(srcFilePath);
            out = new FileOutputStream(destFilePath,true);
            // 获取输入输出通道
            fcIn = in.getChannel();
            fcOut = out.getChannel();
            while (true) {
                try {
                    flout = fcOut.lock();
                    break;
                } catch (OverlappingFileLockException e) {
                    Thread.sleep(1 * 10);
                }
            }

            ByteBuffer buffer = ByteBuffer.allocate(4096);
            while (true) { // clear方法重设缓冲区,使它可以接受读入的数据
                buffer.clear(); // 从输入通道中将数据读到缓冲区
                int r = fcIn.read(buffer);
                if (r == -1) {
                    break;
                }
                // flip方法让缓冲区可以将新读入的数据写入另一个通道
                buffer.flip();
                fcOut.write(buffer);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            flout.release();
            if (in != null && out != null) {
                try {
                    in.close();
                    out.close();
                    System.out.println("关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

posted on 2022-11-29 18:40  枫夜求索阁  阅读(186)  评论(0)    收藏  举报

导航