java多线程操作同一文件的代码

mac2024-06-30  59

public void write(String csvFilePath, StringBuffer sb) { /** * 文件写入以追加的方式写入数据,注意线程安全问题 *String csvFilePath, StringBuffer sb){ */ Thread th=Thread.currentThread(); String threadname = th.getName(); logger.info("current threadName ==[{}] ", threadname); FileOutputStream fos = null; FileChannel fc = null; FileLock fl = null; try { //Constants.COPY_DEVICE_DATA_FILE_PATH 文件路径 fos = new FileOutputStream(csvFilePath, true);

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); fc = fos.getChannel(); while (true) { try { fl = fc.tryLock();//不断的请求锁,如果请求不到,等一秒再请求 break; } catch (Exception e) { logger.info("lock is exist ...... current threadName ==[{}]", threadname); Thread.sleep(1000);//睡1s } } //处理数据 //需要加换行符号 sb.append("\n\r"); byte[] bytes = sb.toString().getBytes(); ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length); buffer.clear(); buffer.put(bytes); buffer.flip(); fc.write(buffer); fl.release(); fc.close(); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); logger.error("current threadName ==[{}] write failed", threadname); } finally { if (fl != null && fl.isValid()) { try { fl.release(); } catch (IOException e) { e.printStackTrace(); logger.error("current threadName ==[{}] release failed", threadname); } } } }
最新回复(0)