多线程读取多个文件(1)(例子)

7 篇文章 0 订阅

这个是我写的三个类,用于多线程操作读取文件内容和写入文件内容,不知道是不是你合你味口。


packagepro;

import java.io.*;
public class ReadFileToWriteOtherFile {

 private File oldFile;
 private File newFile;
 private BufferedReader br;
 private BufferedWriter bw;
 private String totalString="";
 private Boolean flag=true;  //用于标记文件名是否存在  true表示存在

 public ReadFileToWriteOtherFile()
 {
  oldFile=null;
  newFile=null;
  br=null;
  bw=null;
  System.out.println("初始化成功");
 }
 public void readInfoFromFile(StringfileName)
 {

  System.out.println("开始读取");
  try
  {
 
   oldFile=new File(fileName);
   if(oldFile.exists()) //如果文件存在
   {
    System.out.println("存在");
    br=new BufferedReader(newFileReader(oldFile));
    String info=br.readLine(); //读取一行
    while(info!=null)
    {
     totalString+=info;  //将读取到的一行添加到totalString中
     info=br.readLine();  //再读取下一行
     //System.out.println(totalString);
    }
    System.out.println("读取完成,准备写入…………");
   }
   else //如果文件不存在
   {
    System.out.println("文件不存在");
    flag=false;    //标记该文件不存在
   }
  //System.out.println("totalString="+totalString);
  }
  catch(FileNotFoundException e)
  {
  System.out.println(e);System.out.println("开始读取中1");
  }
  catch(IOException e)
  {System.out.println(e);System.out.println("开始读取中2");}
 
 }
 public void writeInfoToFile(StringfileName)
 {
  if(!flag)   //如果标记前面的文件不存在,则return
  {
   flag=true;  //改回原来的文件标记符
   return;
  }
  try
  {
   newFile=new File(fileName);
   if(newFile.exists())  //如果存在,不用创建新文件
   {
    System.out.println("文件存在,可以写入!");
   }
   else //如果不存在,则创建一个新文件
   {
    System.out.println("文件不存在,准备创建新文件");
    newFile.createNewFile();
    System.out.println("文件创建成功,可以写入");
   }
   bw=new BufferedWriter(newFileWriter(newFile,true));
  // System.out.println("totalString="+totalString);
  bw.write(totalString,0,totalString.length());
   bw.flush();  //刷新缓冲区
   System.out.println("写入完成");
   totalString="\r\t";   //清空原来的字符串
  }
  catch(FileNotFoundException e)
  {System.out.println(e);}
  catch(IOException e)
  {System.out.println(e);}
 
 }
}
________________第二个类______一个自定义的线程类____________________
package pro;

import java.lang.Thread;
public class MyThread extends Thread
{
 private int index;  //用于数组的位置
 private String[] fileNames;  //定义一个字符串数组
 ReadFileToWriteOtherFile bftwo=newReadFileToWriteOtherFile();  //定义前面的自定义类
 public MyThread(String[] fileNames,intindex)  //index表示数组位置标号
 {
  this.index=index;
  this.fileNames=fileNames;
 }
 public void run()
 {
 
 bftwo.readInfoFromFile(fileNames[index]);//传入数组中的字符串参数 
  bftwo.writeInfoToFile("b.txt");         //传入写入的目的地文件
  //index++;   //数组位置加1
 System.out.println("==============");//分隔线
 
 }
}
________________第三个类______主程序____________________
package pro;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.*;
public class BeanRunApp {

 /**
  * Method main
  *
  *
  * @param args
  *
  */
 public static void main(String[] args)
 {
  /* ApplicationContext apc=new ClassPathXmlApplicationContext("beans.xml");
   ClassRoomcroom=(ClassRoom)apc.getBean("classRoom");
   croom.out();
   System.out.println("over");
  */
   longstartTime=System.currentTimeMillis();
   String[]a={"a.txt","c.txt","d.txt","e.txt"};  //用一个符品数组保存文件名
 
   for(int i=0;i<a.length;i++)   //用数组的长度来作为循环条件
   { //把这个数组和i的值作为构造函数传入线程类
    MyThread myth=new MyThread(a,i);
   System.out.println("--------------------------------");
    myth.start();   //执行
    System.out.println("当前的线程是:"+myth.getName());  
   }
   long endTime=System.currentTimeMillis();
   System.out.println("耗时:"+(endTime-startTime)+"毫秒");
 }
}

 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
多线程读取文件和写入文件通常是为了提高并发性能,允许程序同时处理多个I/O操作。在多线程环境中,每个线程可以独立地打开文件读取数据或写入数据。下面是一个简单的例子,说明如何使用Java的`Thread`和`BufferedReader`或`PrintWriter`实现这个功能: ```java import java.io.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiThreadedIO { private final String inputFile = "input.txt"; private final String outputFile = "output.txt"; public void readFileAndWrite(String threadName) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(inputFile)); PrintWriter writer = new PrintWriter(new FileWriter(outputFile))) { // 创建线程池 ExecutorService executor = Executors.newSingleThreadExecutor(); // 提交任务给线程池 executor.execute(() -> { String line; while ((line = reader.readLine()) != null) { // 这里可以根据需要对读取到的数据做处理 writer.println(line + " - " + threadName); } writer.close(); }); } catch (IOException e) { System.err.println("Error in reading/writing file by thread " + threadName); e.printStackTrace(); } finally { executor.shutdown(); // 关闭线程池 } } public static void main(String[] args) { MultiThreadedIO io = new MultiThreadedIO(); Thread t1 = new Thread(io::readFileAndWrite, "Thread 1"); Thread t2 = new Thread(io::readFileAndWrite, "Thread 2"); t1.start(); t2.start(); t1.join(); t2.join(); } } ``` 在这个示例中,两个线程分别读取`inputFile`的内容并追加信息到`outputFile`。注意,为了保证线程安全,最好将文件关闭操作放在主线程中,因为同步锁可能会在写入文件时被阻塞。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值