java多线程读写同一个文件的代码

本文提供java多线程分别定时读写同一个文件的样例,其中两个线程,一个每分钟写入当前时间到指定文件,另一个线程读出每分钟新写的内容。

使用简单的Thread.sleep技术实现定时

package test.thread;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Date;

/**
 * 多线程读写同一个文件的样例。
 */
public class ThreadReadWrite {
  public static void main(String[] args) {
    new ThreadWrite().start();
    try {
      Thread.sleep(2000); // 休眠,以免那面还有写好
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    new ThreadRead().start();
  }
}

class ThreadWrite extends Thread {
  File file = new File("test.txt");

  @Override
  public void run() {
    try {
      while (true) {
        FileWriter out = new FileWriter(file, true);// 追加写入
        out.write(new Date() + "/n");
        out.flush();
        out.close();
        Thread.sleep(3000); // 我这里间隔改成3秒,方便测试
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

class ThreadRead extends Thread {
  File file = new File("test.txt");

  @Override
  public void run() {
    try {
      BufferedReader reader = new BufferedReader(new FileReader(file));
      while (true) {
        System.out.println(reader.readLine());
        Thread.sleep(3000); // 我这里间隔改成3秒,方便测试
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


如果真的要求严格,应该用Timer继续比较精确的控制。

package test.thread;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 使用Timer定时器进行同一文件的读写。
 */
public class ThreadReadWriteTimer {
  static File file = new File("test.txt");

  public static void main(String[] args) {
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
      @Override
      public void run() {
        FileWriter out;
        try {
          out = new FileWriter(file, true);
          // 追加写入
          out.write(new Date() + "/n");
          out.flush();
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }, 0, 3000);
    timer.scheduleAtFixedRate(new TimerTask() {
      BufferedReader reader = null;
      {
        try {
          reader = new BufferedReader(new FileReader(file));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      @Override
      public void run() {
        try {
          System.out.println(reader.readLine());
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }, 1000, 3000);
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一个Java多线程读写文件excel的工具类。您可以使用Apache POI库来读写excel文件,同时使用Java多线程来提高读写效率。以下是一个简单的示例代码: ``` import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelReadWriteUtil { private static final int THREAD_POOL_SIZE = 10; public static void readWriteExcel(File inputFile, File outputFile) throws IOException { Workbook workbook = new XSSFWorkbook(new FileInputStream(inputFile)); Sheet sheet = workbook.getSheetAt(0); int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum(); ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); for (int i = 1; i <= rowCount; i++) { Row row = sheet.getRow(i); executor.execute(new ExcelRowProcessor(row, outputFile)); } executor.shutdown(); while (!executor.isTerminated()) { // Wait for all threads to finish } workbook.close(); } private static class ExcelRowProcessor implements Runnable { private final Row row; private final File outputFile; public ExcelRowProcessor(Row row, File outputFile) { this.row = row; this.outputFile = outputFile; } @Override public void run() { try { Workbook workbook = new XSSFWorkbook(new FileInputStream(outputFile)); Sheet sheet = workbook.getSheetAt(0); int rowNum = sheet.getLastRowNum() + 1; Row newRow = sheet.createRow(rowNum); for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = newRow.createCell(j); cell.setCellValue(row.getCell(j).getStringCellValue()); } FileOutputStream outputStream = new FileOutputStream(outputFile); workbook.write(outputStream); workbook.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 您可以将输入文件和输出文件作为参数传递给`readWriteExcel`方法。该方法会使用多线程读取输入文件的每一行,并将每一行写入输出文件。每个线程都会创建一个新的工作簿对象,并将每一行写入输出文件。请注意,此示例代码仅适用于.xlsx格式的Excel文件。如果您需要处理.xls格式的文件,则需要使用HSSFWorkbook而不是XSSFWorkbook。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值