導航:首頁 > 文件教程 > java多線程讀文件

java多線程讀文件

發布時間:2023-05-27 01:27:08

A. java 利用RandomAccessFile實現多線程並發讀寫一個大文件

樓主,如果寫,先判斷要寫多大的文件、然後分段寫,各線程寫自己的段

如果讀,也是先得到文件大小、再分段,然後各線程讀自己的段

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

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

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

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

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

不可行。
多線程能夠提高效率是因為現在的cpu普遍是多核cpu, 多條線程可以在版多個內核中權同時執行來提高計算效率。但是計算機磁碟的磁頭只有一個,即使多條線程去讀也並不能提高讀取效率,反而因為多線程的上下文切換問題會耗時更久。

E. 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() {
@
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();
}
}

F. Java如何實現多線程傳輸文件,就像迅雷下載一樣,開十多個線程分段傳送位元組流

程序分Server和Client

伺服器端打開偵聽的埠,一有客戶端連接就創建兩個新的線程來負責這個連接

一個負責客戶端發送的信息(ClientMsgCollectThread 類),

另一個負責通過該Socket發送數據(ServerMsgSendThread )

Server.java代碼如下:

/*
* 創建日期 2009-3-7
*
* TODO 要更改此生成的文件的模板,請轉至
* 窗口 - 首選項 - Java - 代碼樣式 - 代碼模板
*/
package faue.MutiUser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
* 伺服器端
*
* @author Faue
*/
public class Server extends ServerSocket {

private static final int SERVER_PORT = 10000;

/**
* 構造方法,用於實現連接的監聽
*
* @throws IOException
*/
public Server() throws IOException {
super(SERVER_PORT);

try {
while (true) {
Socket socket = super.accept();

new Thread(new ClientMsgCollectThread(socket), "getAndShow"
+ socket.getPort()).start();
new Thread(new ServerMsgSendThread(socket), "send"
+ socket.getPort()).start();

}
} catch (IOException e) {
e.printStackTrace();
}

}

public static void main(String[] args) throws IOException {
new Server();
}

/**
* 該類用於創建接收客戶端發來的信息並顯示的線程
*
* @author Faue
* @version 1.0.0
*/
class ClientMsgCollectThread implements Runnable {

private Socket client;

private BufferedReader in;

private StringBuffer inputStringBuffer = new StringBuffer("Hello");

/**
* 得到Socket的輸入流
*
* @param s
* @throws IOException
*/
public ClientMsgCollectThread(Socket s) throws IOException {
client = s;

in = new BufferedReader(new InputStreamReader(client
.getInputStream(), "GBK"));
}

public void run() {
try {

while (!client.isClosed()) {
inputStringBuffer.delete(0, inputStringBuffer.length());
inputStringBuffer.append(in.readLine());

System.out.println(getMsg(inputStringBuffer.toString()));
}
} catch (IOException e) {
//e.printStackTrace();
System.out.println(client.toString() + " is closed!");

}
}

/**
* 構造顯示的字元串
*
* @param line
* @return
*/
private String getMsg(String line) {
return client.toString() + " says:" + line;
}

}

/**
* 該類用於創建發送數據的線程
*
* @author Faue
* @version 1.0.0
*/
class ServerMsgSendThread implements Runnable {

private Socket client;

private PrintWriter out;

private BufferedReader keyboardInput;

private StringBuffer outputStringBuffer = new StringBuffer("Hello");

/**
* 得到鍵盤的輸入流
*
* @param s
* @throws IOException
*/
public ServerMsgSendThread(Socket s) throws IOException {
client = s;

out = new PrintWriter(client.getOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(System.in));

}

public void run() {
try {

while (!client.isClosed()) {
outputStringBuffer.delete(0, outputStringBuffer.length());
outputStringBuffer.append(keyboardInput.readLine());

out.println(outputStringBuffer.toString());
}
} catch (IOException e) {
//e.printStackTrace();
System.out.println(client.toString() + " is closed!");

}
}

}

}

客戶端:

實現基於IP地址的連接,連接後也創建兩個線程來實現信息的發送和接收

/*
* 創建日期 2009-3-7
*
*/
package faue.MutiUser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
* 客戶端
*
* @author Faue
*/
public class Client {

private Socket mySocket;

/**
* 創建線程的構造方法
*
* @param IP
* @throws IOException
*/
public Client(String IP) throws IOException {

try {
mySocket = new Socket(IP, 10000);
new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"
+ mySocket.getPort()).start();
new Thread(new ClientMsgSendThread(mySocket), "send"
+ mySocket.getPort()).start();

} catch (IOException e) {
//e.printStackTrace();
System.out.println("Server.IP:" + IP
+ " port:10000 can not be Connected");
}
}

public static void main(String[] args) throws IOException {
try {
new Client(args[0]);
} catch (Exception e) {
System.out.println("輸入的IP地址錯誤");
}
}

/**
* 該類用於創建接收服務端發來的信息並顯示的線程
*
* @author Faue
* @version 1.0.0
*/
class ServerMsgCollectThread implements Runnable {

private Socket client;

private BufferedReader in;

private StringBuffer inputStringBuffer = new StringBuffer("Hello");

/**
* 得到Socket的輸入流
*
* @param s
* @throws IOException
*/
public ServerMsgCollectThread(Socket s) throws IOException {
client = s;

in = new BufferedReader(new InputStreamReader(client
.getInputStream(), "GBK"));
}

public void run() {
try {

while (!client.isClosed()) {
inputStringBuffer.delete(0, inputStringBuffer.length());
inputStringBuffer.append(in.readLine());
System.out.println(getMsg(inputStringBuffer.toString()));
}
} catch (IOException e) {
//e.printStackTrace();
System.out.println(client.toString() + " is closed!");
System.exit(0);
}
}

/**
* 構造輸入字元串
*
* @param line
* @return
*/
private String getMsg(String line) {
return client.toString() + " says:" + line;
}

}

/**
* 該類用於創建發送數據的線程
*
* @author Faue
* @version 1.0.0
*/
class ClientMsgSendThread implements Runnable {

private Socket client;

private PrintWriter out;

private BufferedReader keyboardInput;

private StringBuffer outputStringBuffer = new StringBuffer("Hello");

/**
* 得到鍵盤的輸入流
*
* @param s
* @throws IOException
*/
public ClientMsgSendThread(Socket s) throws IOException {
client = s;

out = new PrintWriter(client.getOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(System.in));

}

public void run() {
try {

while (!client.isClosed()) {
outputStringBuffer.delete(0, outputStringBuffer.length());
outputStringBuffer.append(keyboardInput.readLine());

out.println(outputStringBuffer.toString());
}
out.println("--- See you, bye! ---");
} catch (IOException e) {
//e.printStackTrace();
System.out.println(client.toString() + " is closed!");
System.exit(0);
}
}

}

}

如果對您有幫助,請記得採納為滿意答案,謝謝!祝您生活愉快!

vaela

G. 求多線程讀取一個文件,然後寫到另外一個文件中的Java實現。

這個是我寫的三個類,用於多線程操作讀取文件內容和寫入文件內容,不知道是不是你合你味口。
________________第一個類______讀取內容__寫入內容____________________
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多線程讀文件相關的資料

熱點內容
html5中加入js 瀏覽:441
美服applestoreid 瀏覽:889
微信數據文件能清嗎 瀏覽:107
圖片編輯到文件里列印怎麼有重影 瀏覽:593
舟山四軸編程培訓哪個學校好 瀏覽:542
沒加別人QQ可以發word文件 瀏覽:51
手機桌面的文件路徑 瀏覽:892
改款新寶來怎麼使用手機app 瀏覽:281
dede工具 瀏覽:507
5g網盟app怎麼下載 瀏覽:486
微信備份老是連接中斷 瀏覽:886
出台多少份文件 瀏覽:380
鞋子怎麼搭配衣服的app 瀏覽:755
文件名使用的通配符的符號是什麼 瀏覽:916
lol分卷文件損壞怎麼辦 瀏覽:276
6分管車螺紋怎麼編程 瀏覽:732
海口農商銀行信用卡app是什麼 瀏覽:770
win10任務欄文件夾我的電腦 瀏覽:14
安卓nba2k18 瀏覽:776
文件夾密碼怎麼修改密碼 瀏覽:271

友情鏈接