導航:首頁 > 編程語言 > java多線程讀文件

java多線程讀文件

發布時間:2022-06-01 01:23:47

java 怎麼用10個線程去讀取文件夾里100個txt文件中的內容,讀完之後同步寫到一個文件中去。

這個是我寫的三個類,用於多線程操作讀取文件內容和寫入文件內容,不知道是不是你合你味口。
________________第一個類______讀取內容__寫入內容____________________
package pro;

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(String fileName)
{

System.out.println("開始讀取");
try
{

oldFile=new File(fileName);
if(oldFile.exists()) //如果文件存在
{
System.out.println("存在");
br=new BufferedReader(new FileReader(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(String fileName)
{
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(new FileWriter(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=new ReadFileToWriteOtherFile(); //定義前面的自定義類
public MyThread(String[] fileNames,int index) //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.;
import java.io.*;
public class BeanRunApp {

/**
* Method main
*
*
* @param args
*
*/
public static void main(String[] args)
{
/* ApplicationContext apc=new ("beans.xml");
ClassRoom croom=(ClassRoom)apc.getBean("classRoom");
croom.out();
System.out.println("over");
*/
long startTime=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)+"毫秒");
}
}

㈡ 「java」中多線程按行讀取txt且每個線程讀的內容不能重復,這么求「demo」

你把原來程序中直接讀的地方,改成調用上面的函數,由該函數統一讀行。這樣,不管是你有 N 個線程,還是一個線程,都不會發生讀的行重復,或者讀的行不完整的現象了。

為了充分利用多線程讀取,就需要把文件劃分成多個區域,供每個線程讀取。那麼就需要有一個演算法來計算出每個線程讀取的開始位置和結束位置。那麼首先根據配置的線程數和文件的總長度計,算出每個線程平均分配的讀取長度。

但是有一點,由於文件是純文本文件,必須按行來處理,如果分割點在某一行中間,那麼這一行數據就會被分成兩部分,分別由兩個線程同時處理,這種情況是不能出現的。所以各個區域的結束點上的字元必須是換行符。第一個區域的開始位置是0,結束位置首先設為(文件長度/線程數),如果結束點位置不是換行符,就只能加1,直到是換行符位置。

㈢ java多線程同時讀取一個文件,這個方法可行嗎

不可行。每次讀取文件都需要創建緩存文件流,很占內存,而且多次讀取實際上也是一個文件,還不如直接讀取文件,之後通過條件多次獲取需要的內容來的實際。
可以通過BufferedReader
流的形式進行流緩存,之後通過readLine方法獲取到緩存的內容。
BufferedReader
bre
=
null;
try
{
String
file
=
"D:/test/test.txt";
bre
=
new
BufferedReader(new
FileReader(file));//此時獲取到的bre就是整個文件的緩存流
while
((str
=
bre.readLine())!=
null)
//
判斷最後一行不存在,為空結束循環
{
System.out.println(str);//原樣輸出讀到的內容,此處可以添加條件進行不同的處理
};
備註:
流用完之後必須close掉,如上面的就應該是:bre.close(),否則bre流會一直存在,直到程序運行結束。

㈣ java 多線程讀取txt 文件

多線程將讀取的數據全部讀取到一個Buffer裡面去,然後再通過Buffer去處理,也就是生產者消費者模型,你將txt讀取到一個ByteBuffer或者是大位元組數組隊列裡面都可以,然後通過其它處理線程進行按行分隔

㈤ Java如何使用多線程讀取40M的文件

1,讀取文件大小(比如大小是200K)。
2,啟動5個線程,第一個線程從其實讀,第二個線程跳過40在讀40。。

㈥ java多線程讀寫文件

public static void main(String[] args) {
File data = new File("data.txt");
try {
InputStreamReader read = new InputStreamReader(new FileInputStream(
data), "UTF-8");
final BufferedReader bufferedReader = new BufferedReader(read);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
String lineTXT = null;
synchronized (bufferedReader) {
try {
while ((lineTXT = bufferedReader.readLine()) != null) {
System.out.println(Thread.currentThread()+":"+lineTXT);
bufferedReader.notify();
bufferedReader.wait();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
bufferedReader.notifyAll();
}
}
}
}).start();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

㈦ java多線程如何實現特定線程讀取磁碟上特定標識的文件

classWorkerimplementsRunnable{
privateStringfilename;

publicWorker(Stringfilename){
this.filename=filename;
}

@Override
publicvoidrun(){
FileReaderfr=newFileReader(filename);
fr.read();//讀一個字元
...//以及其他操作
fr.close();
}
}

publicclassFoobar{
publicstaticvoidmain(String[]args){
Workerw1=newWorker("a.txt");
Workerw2=newWorker("b.txt");
Workerw3=newWorker("c.txt")
Threadt1=newThread(w1);
Threadt2=newThread(w2);
Threadt3=newThread(w3);
t1.start();
t2.start();
t3.start();
}
}

㈧ JAVA中如何用線程讀取一個文件里的數據!

import java.io.*;
class DownThread extends Thread {
//定義位元組數組(取水的竹筒)的長度
private final int BUFF_LEN = 32;
//定義讀取的起始點
private long start;
//定義讀取的結束點
private long end;
//讀取文件對應的輸入流
private InputStream is;
//將讀取到的位元組輸出到raf中
private RandomAccessFile raf;

//構造器,傳入輸入流,輸出流和讀取起始點、結束點
public DownThread(long start, long end, InputStream is, RandomAccessFile raf) {
//輸出該線程負責讀取的位元組位置
System.out.println(start + "---->" + end);
this.start = start;
this.end = end;
this.is = is;
this.raf = raf;
}

public void run() {
try {
is.skip(start);
raf.seek(start);
//定義讀取輸入流內容的的緩存數組(竹筒)
byte[] buff = new byte[BUFF_LEN];
//本線程負責讀取文件的大小
long contentLen = end - start;
//定義最多需要讀取幾次就可以完成本線程的讀取
long times = contentLen / BUFF_LEN + 4;
//實際讀取的位元組數
int hasRead = 0;
for (int i = 0; i < times; i++) {
hasRead = is.read(buff);
//如果讀取的位元組數小於0,則退出循環!
if (hasRead < 0) {
break;
}
raf.write(buff, 0, hasRead);
}
} catch (Exception ex) {
ex.printStackTrace();
}
//使用finally塊來關閉當前線程的輸入流、輸出流
finally {
try {
if (is != null) {
is.close();
}
if (raf != null) {
raf.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

public class MutilDown {
public static void main(String[] args) {
final int DOWN_THREAD_NUM = 4;
final String OUT_FILE_NAME = "d:/勇敢的心.rmvb";
InputStream[] isArr = new InputStream[DOWN_THREAD_NUM];
RandomAccessFile[] outArr = new RandomAccessFile[DOWN_THREAD_NUM];
try {

isArr[0] = new FileInputStream("d:/勇敢的心.rmvb");
long fileLen = getFileLength(new File("d:/勇敢的心.rmvb"));
System.out.println("文件的大小" + fileLen);
//以輸出文件名創建第一個RandomAccessFile輸出流
outArr[0] = new RandomAccessFile(OUT_FILE_NAME, "rw");
//創建一個與文件相同大小的空文件
for (int i = 0; i < fileLen; i++) {
outArr[0].write(0);
}
//每線程應該讀取的位元組數
long numPerThred = fileLen / DOWN_THREAD_NUM;
//整個文件整除後剩下的余數
long left = fileLen % DOWN_THREAD_NUM;
for (int i = 0; i < DOWN_THREAD_NUM; i++) {
//為每個線程打開一個輸入流、一個RandomAccessFile對象,
//讓每個線程分別負責讀取文件的不同部分。
if (i != 0) {

isArr[i] = new FileInputStream("d:/勇敢的心.rmvb");
//以指定輸出文件創建多個RandomAccessFile對象
outArr[i] = new RandomAccessFile(OUT_FILE_NAME, "rw");
}
if (i == DOWN_THREAD_NUM - 1) {
//最後一個線程讀取指定numPerThred+left個位元組
new DownThread(i * numPerThred, (i + 1) * numPerThred
+ left, isArr[i], outArr[i]).start();
} else {
//每個線程負責讀取一定的numPerThred個位元組
new DownThread(i * numPerThred, (i + 1) * numPerThred,
isArr[i], outArr[i]).start();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

public static long getFileLength(File file) {
long length = 0;
//獲取文件的長度
long size = file.length();
length = size;
return length;
}
}

㈨ 一個文件能同時被多個java線程讀取嗎

可以。但是由於機械磁碟只能同時一個線程訪問,所以多線程的讀取效率可能還不如單線程。

㈩ java中怎麼用多個線程同時對一個文件讀取,最終將文件內容保存到一個位元組數組中去呢

多線程讀取文件在一塊硬碟上沒用,瓶頸在硬碟I/O,而不在CPU和內存。讀取文件時,CPU不用復雜的計算工作,只是數據傳輸而已,多線程反而造成磁頭來回移動,效率不高。如果是兩塊以上的硬碟,可以用不同的線程訪問不同的硬碟,效率比單線程要高
而且多線程操作同一文件除了效率還會有多線程問題,多個線程同時往數組里存數據還會有線程安全問題,如果不同步處理讀取的文件就是錯誤的。
如果讀取的話只能設置每個線程各自讀取偏 移量
讀取文件大小(比如大小是200K)。 2,啟動5個線程,第一個線程讀到40,第二個線程跳過40在讀到80,總之得合理安排好各個線程讀取的大小。這樣才能不重復讀取。大數據處理框架maprece原理和此類似

閱讀全文

與java多線程讀文件相關的資料

熱點內容
下載釘釘app是什麼 瀏覽:222
什麼伺服器支持雲播放 瀏覽:835
什麼app進貨牛排比較好 瀏覽:107
為什麼鴻蒙用安卓app 瀏覽:82
手相面相pdf 瀏覽:374
軍犬不聽命令追出大門 瀏覽:913
程序員必背97件事 瀏覽:939
雲伺服器python怎麼讀取 瀏覽:30
哪裡買雲伺服器劃算 瀏覽:236
四川日報pdf 瀏覽:965
按摩解壓助眠小姐姐 瀏覽:411
風冷壓縮機水冷卻器 瀏覽:879
伺服器播放器如何打開方式 瀏覽:790
phppython快 瀏覽:366
pdf轉換word免費版 瀏覽:37
二手的有什麼APP 瀏覽:329
伺服器的應用鏡像是什麼 瀏覽:153
命令行的使用方法 瀏覽:514
怎麼讓圖片左右壓縮 瀏覽:656
白鹿原pdf 瀏覽:433