導航:首頁 > 編程語言 > java文件讀取大文件內容

java文件讀取大文件內容

發布時間:2024-10-01 11:16:49

A. java中如何從文件中讀取數據

1.package txt;
2.
3.import java.io.BufferedReader;
4.import java.io.File;
5.import java.io.FileInputStream;
6.import java.io.InputStreamReader;
7.
8./**
9. * 讀取TXE數據
10. */
11.public class ReadTxtUtils {
12. public static void main(String arg[]) {
13. try {
14. String encoding = "GBK"; // 字元編碼(可解決中文亂碼問題 )
15. File file = new File("c:/aa.txt");
16. if (file.isFile() && file.exists()) {
17. InputStreamReader read = new InputStreamReader(
18. new FileInputStream(file), encoding);
19. BufferedReader bufferedReader = new BufferedReader(read);
20. String lineTXT = null;
21. while ((lineTXT = bufferedReader.readLine()) != null) {
22. System.out.println(lineTXT.toString().trim());
23. }
24. read.close();
25. }else{
26. System.out.println("找不到指定的文件!");
27. }
28. } catch (Exception e) {
29. System.out.println("讀取文件內容操作出錯");
30. e.printStackTrace();
31. }
32. }
33.}
java讀取TXT文件中的數據,每一行就是一個數,返回一個數組,代碼?
?
List list=new ArrayList();
BufferedReader br=new BufferReader(new InputStreamReader(new FileInputStream(new File("in.txt"))));
String str=null;
while((str=br.readLine())!=null)
{
list.add(new Integer(str));

}
Integer[] i=new Integer[list.size()];
list.toArray(i);

TXT文本中如據形如:
123
456
789

讀入二維數組效果為:
temp[0][]={1,2,3};
temp[1][]={4,5,6};
temp[2][]={7,8,9};

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.*;

public class xx{
public static void main(String[]args){
String s;
int[][]save=new int[3][3];
try{
BufferedReader in =new BufferedReader(new FileReader("C:\\txt.txt"));
int i=0;
while((s=in.readLine())!=null){
save[i][0]=Integer.parseInt(s.substring(0,1));
save[i][1]=Integer.parseInt(s.substring(1,2));
save[i][2]=Integer.parseInt(s.substring(2,3));
i++;
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++){
System.out.print(save[i][j]);
}
System.out.println();
}
}
}


?
BufferedReader bf=new BufferedReader(new FileReader("Your file"));
String lineContent=null;
int i = 0;
int [][] temp = new int [3][];
while((lineContent=bf.readLine())!=null){
String [] str = lineContent.split("\\d");// 將 lineContent 按數字拆分
for(int j = 0; j < str.length(); j++){
int [i][j] = Integer.parseInt(str[j]);
}
i++;
}

scp|cs|ff|201101
這是d:\\a.txt的數據,與「|」分割取數據出來,保存在變數a;b;c;d里

import java.io.*;

public class Test{
public static void main(String[] args)throws Exception{
String a, b, c, d;
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader("d:\\a.txt"));
String s = br.readLine();
while(s != null){
sb.append(s);
s = br.readLine();
}
s = sb.toString();
String[] str = s.split("|");
a = str[0];
b = str[0];
c = str[0];
d = str[0];
}
}

B. Java讀取文件內容(Java讀取文件內容為字元串)

JAVA中讀取文件(二進制,字元)內容的幾種方

JAVA中讀取文件內容的方法有很多,比如按位元組讀取文件內容,按字元讀取文件內容,按行讀取文件內容,隨機讀取文件內容等方法,本文就以上方法的具體實現給出代碼,需要的可以直接復制使用

publicclassReadFromFile{

/**

*以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。

*/

(StringfileName){

Filefile=newFile(fileName);

InputStreamin=null;

try{

System.out.println("以位元組為單位讀取文件內容,一次讀一個位元組:");

//一次讀一個位元組

in=newFileInputStream(file);

inttempbyte;

while((tempbyte=in.read())!=-1){

System.out.write(tempbyte);

}

in.close();

}catch(IOExceptione){

e.printStackTrace();

return;

}

try{

System.out.println("以位元組為單位讀取文件內容,一次讀多個位元組:");

//一次讀多個位元組

byte[]tempbytes=newbyte[100];

intbyteread=0;

in=newFileInputStream(fileName);

ReadFromFile.showAvailableBytes(in);

//讀入多個位元組到位元組數組中,byteread為一次讀入的位元組數

while((byteread=in.read(tempbytes))!=-1){

System.out.write(tempbytes,0,byteread);

}

}catch(Exceptione1){

e1.printStackTrace();

}finally{

if(in!=null){

try{

in.close();

}catch(IOExceptione1){

}

}

}

}

/**

*以字元為單位讀取文件,常用於讀文本,數字等類型的文件

*/

(StringfileName){

Filefile=newFile(fileName);

Readerreader=null;

try{

System.out.println("以字元為單位讀取文件內容,一次讀一個位元組:");

//一次讀一個字元

reader=newInputStreamReader(newFileInputStream(file));

inttempchar;

while((tempchar=reader.read())!=-1){

//對於windows下, 這兩個字元在一起時,表示一個換行。

//但如果這兩個字元分開顯示時,會換兩次行。

//因此,屏蔽掉 ,或者屏蔽 。否則,將會多出很多空行。

if(((char)tempchar)!=' '){

System.out.print((char)tempchar);

}

}

reader.close();

}catch(Exceptione){

e.printStackTrace();

}

try{

System.out.println("以字元為單位讀取文件內容,一次讀多個位元組:");

//一次讀多個字元

char[]tempchars=newchar[30];

intcharread=0;

reader=newInputStreamReader(newFileInputStream(fileName));

//讀入多個字元到字元數組中,charread為一次讀取字元數

while((charread=reader.read(tempchars))!=-1){

//同樣屏蔽掉 不顯示

if((charread==tempchars.length)

(tempchars[tempchars.length-1]!=' ')){

System.out.print(tempchars);

}else{

for(inti=0;icharread;i++){

if(tempchars[i]==' '){

continue;

}else{

System.out.print(tempchars[i]);

}

}

}

}

}catch(Exceptione1){

e1.printStackTrace();

}finally{

if(reader!=null){

try{

reader.close();

}catch(IOExceptione1){

}

}

}

}

/**

*以行為單位讀取文件,常用於讀面向行的格式化文件

*/

(StringfileName){

Filefile=newFile(fileName);

BufferedReaderreader=null;

try{

System.out.println("以行為單位讀取文件內容,一次讀一整行:");

reader=newBufferedReader(newFileReader(file));

StringtempString=null;

intline=1;

//一次讀入一行,直到讀入null為文件結束

while((tempString=reader.readLine())!=null){

//顯示行號

System.out.println("line"+line+":"+tempString);

line++;

}

reader.close();

}catch(IOExceptione){

e.printStackTrace();

}finally{

if(reader!=null){

try{

reader.close();

}catch(IOExceptione1){

}

}

}

}

/**

*隨機讀取文件內容

*/

(StringfileName){

RandomAccessFilerandomFile=null;

try{

System.out.println("隨機讀取一段文件內容:");

//打開一個隨機訪問文件流,按只讀方式

randomFile=newRandomAccessFile(fileName,"r");

//文件長度,位元組數

longfileLength=randomFile.length();

//讀文件的起始位置

intbeginIndex=(fileLength4)?4:0;

//將讀文件的開始位置移到beginIndex位置。

randomFile.seek(beginIndex);

byte[]bytes=newbyte[10];

intbyteread=0;

//一次讀10個位元組,如果文件內容不足10個位元組,則讀剩下的位元組。

//將一次讀取的位元組數賦給byteread

while((byteread=randomFile.read(bytes))!=-1){

System.out.write(bytes,0,byteread);

}

}catch(IOExceptione){

e.printStackTrace();

}finally{

if(randomFile!=null){

try{

randomFile.close();

}catch(IOExceptione1){

}

}

}

}

/**

*顯示輸入流中還剩的位元組數

*/

(InputStreamin){

try{

System.out.println("當前位元組輸入流中的位元組數為:"+in.available());

}catch(IOExceptione){

e.printStackTrace();

}

}

publicstaticvoidmain(String[]args){

StringfileName="C:/temp/newTemp.txt";

ReadFromFile.readFileByBytes(fileName);

ReadFromFile.readFileByChars(fileName);

ReadFromFile.readFileByLines(fileName);

ReadFromFile.readFileByRandomAccess(fileName);

}

}

Java如何讀取txt文件的內容?

java讀取txt文件內容。可以作如下理解:

首先獲得一個文件句柄。Filefile=newFile();file即為文件句柄。兩人之間連通電話網路了。接下來可以開始打電話了。

通過這條線路讀取甲方的信息:newFileInputStream(file)目前這個信息已經讀進來內存當中了。接下來需要解讀成乙方可以理解的東西

既然你使用了FileInputStream()。那麼對應的需要使用InputStreamReader()這個方法進行解讀剛才裝進來內存當中的數據

解讀完成後要輸出呀。那當然要轉換成IO可以識別的數據呀。那就需要調用位元組碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt文件中的每一行數據哈。

package?com.campu;

?

import?java.io.BufferedInputStream;

import?java.io.BufferedReader;

import?java.io.File;

import?java.io.FileInputStream;

import?java.io.InputStreamReader;

import?java.io.Reader;

?

/**

?*?@author?Java團長

?*?H20121012.java

?*?2017-10-29上午11:22:21

?*/

public?class?H20121012?{

????/**

?????*?功能:Java讀取txt文件的內容

?????*?步驟:1:先獲得文件句柄

?????*?2:獲得文件句柄當做是輸入一個位元組碼流,需要對這個輸入流進行讀取

?????*?3:讀取到輸入流後,需要讀取生成位元組流

?????*?4:一行一行的輸出。readline()。

?????*?備註:需要考慮的是異常情況

?????*?@param?filePath

?????*/

????public?static?void?readTxtFile(String?filePath){

????????try?{

????????????????String?encoding="GBK";

????????????????File?file=new?File(filePath);

????????????????if(file.isFile()??file.exists()){?//判斷文件是否存在

????????????????????InputStreamReader?read?=?new?InputStreamReader(

????????????????????new?FileInputStream(file),encoding);//考慮到編碼格式

????????????????????BufferedReader?bufferedReader?=?new?BufferedReader(read);

????????????????????String?lineTxt?=?null;

????????????????????while((lineTxt?=?bufferedReader.readLine())?!=?null){

????????????????????????System.out.println(lineTxt);

????????????????????}

????????????????????read.close();

????????}else{

????????????System.out.println("找不到指定的文件");

????????}

????????}?catch?(Exception?e)?{

????????????System.out.println("讀取文件內容出錯");

????????????e.printStackTrace();

????????}

?????

????}

?????

????public?static?void?main(String?argv[]){

????????String?filePath?=?"L:\Apache\htdocs\res\20121012.txt";

//??????"res/";

????????readTxtFile(filePath);

????}

?????

?????

?

}

我有一個微信公眾號,經常會分享一些Java技術相關的干貨文章,還有一些學習資源。

如果你需要的話,可以用微信搜索「Java團長」或者「javatuanzhang」關注。

java中怎樣從文件中讀取數據?

分為讀位元組,讀字元兩種讀法x0dx0a◎◎◎FileInputStream位元組輸入流讀文件◎◎◎x0dx0apublicclassMaintest{(String[]args)throwsIOException{x0dx0ax0dx0aFilef=newFile("G:\justforfun\xiangwei.txt");=newFileInputStream(f);x0dx0ax0dx0abyte[]bs=newbyte[1024];x0dx0ax0dx0aintcount=0;x0dx0awhile((count=fin.read(bs))0)x0dx0a{x0dx0ax0dx0aStringstr=newString(bs,0,count);//反復定義新變數:每一次都重新定義新變數,接收新讀取的數據x0dx0ax0dx0aSystem.out.println(str);//反復輸出新變數:每一次都輸出重新定義的新變數x0dx0a}x0dx0afin.close();x0dx0a}x0dx0a}x0dx0ax0dx0a◎◎◎FileReader字元輸入流讀文件◎◎◎x0dx0apublicclassMaintest{x0dx0apublicstaticvoidmain(String[]args)throwsIOException{x0dx0ax0dx0aFilef=newFile("H:\justforfun\xiangwei.txt");x0dx0ax0dx0aFileReaderfre=newFileReader(f);x0dx0ax0dx0aBufferedReaderbre=newBufferedReader(fre);x0dx0ax0dx0aStringstr="";x0dx0awhile((str=bre.readLine())!=null)//●判斷最後一行不存在,為空x0dx0a{x0dx0aSystem.out.println(str);x0dx0a}x0dx0abre.close();x0dx0afre.close();x0dx0ax0dx0a}x0dx0ax0dx0a}

java中在怎麼讀取文件夾中的內容

以下java程序的作用是將當前目錄及其子目錄中的.java文件收集到collection.txt文件中,並添加行號,你可以參考一下。

importjava.io.*;

publicclassCollection

{

publicstaticvoidmain(String[]args)throwsException

{

finalStringF=".\collection.txt";

FW=newFileWriter(newFile(F));

Collection.ProcessDirectory(newFile("."));

Collection.FW.flush();

Collection.FW.close();

}

(Filed)throwsException

{

File[]ds=null;

Collection.ProcessJavaFile(d);

ds=d.listFiles(Collection.DFilter);

for(inti=0;ids.length;i++)

{

Collection.ProcessDirectory(ds[i]);

}

}

(Filed)throwsException

{

Stringline=null;

LineNumberReaderlnr=null;

File[]fs=d.listFiles(Collection.FNFilter);

for(inti=0;ifs.length;i++)

{

lnr=newLineNumberReader(newFileReader(fs[i]));

Collection.FW.write(fs[i].getCanonicalPath()+" ");

System.out.println(fs[i].getCanonicalPath());

while(null!=(line=lnr.readLine()))

{

Collection.FW.write(""+lnr.getLineNumber()+""+line+" ");

System.out.println(""+lnr.getLineNumber()+""+line);

}

Collection.FW.write(" ");

System.out.println();

}

}

privatestaticFileWriterFW;

=newFilenameFilter()

{

publicbooleanaccept(Filedir,Stringname)

{

returnname.endsWith(".java");

}

};

=newFileFilter()

{

publicbooleanaccept(Filepathname)

{

returnpathname.isDirectory();

}

};

}

java中怎樣從一個文件中讀取文件信息

java讀取文件路徑、所佔空間大小等文件消息,主要是使用FileInputStream類來操作,示例如下:

import?java.io.File;

C. 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)+"毫秒");
}
}

D. java 如何讀取大文件

以下將從常規方法談起,通過對比來說明應該如何使用java讀取大文件。

1、常規:在內存中讀取
讀取文件行的標准方式是在內存中讀取,Guava 和Apache Commons IO都提供了如下所示快速讀取文件行的方法:
Files.readLines(new File(path), Charsets.UTF_8);
FileUtils.readLines(new File(path));
這種方法帶來的問題是文件的所有行都被存放在內存中,當文件足夠大時很快就會導致程序拋出OutOfMemoryError 異常。
例如:讀取一個大約1G的文件:
@Test
public void givenUsingGuava_whenIteratingAFile_thenWorks() throws IOException {
String path = ...
Files.readLines(new File(path), Charsets.UTF_8);
}
這種方式開始時只佔用很少的內存:(大約消耗了0Mb內存)
然而,當文件全部讀到內存中後,我們最後可以看到(大約消耗了2GB內存):
這意味這一過程大約耗費了2.1GB的內存——原因很簡單:現在文件的所有行都被存儲在內存中。
把文件所有的內容都放在內存中很快會耗盡可用內存——不論實際可用內存有多大,這點是顯而易見的。
此外,我們通常不需要把文件的所有行一次性地放入內存中——相反,我們只需要遍歷文件的每一行,然後做相應的處理,處理完之後把它扔掉。所以,這正是我們將要做的——通過行迭代,而不是把所有行都放在內存中。

2、文件流
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
// System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
這種方案將會遍歷文件中的所有行——允許對每一行進行處理,而不保持對它的引用。總之沒有把它們存放在內存中:(大約消耗了150MB內存)

3、Apache Commons IO流
同樣也可以使用Commons IO庫實現,利用該庫提供的自定義LineIterator:
LineIterator it = FileUtils.lineIterator(theFile, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
LineIterator.closeQuietly(it);
}
由於整個文件不是全部存放在內存中,這也就導致相當保守的內存消耗:(大約消耗了150MB內存)

閱讀全文

與java文件讀取大文件內容相關的資料

熱點內容
dwa演算法可以用在哪裡 瀏覽:971
怎麼玩奇思妙想app 瀏覽:79
javaxmlmap 瀏覽:577
為什麼加密程序顯示exe 瀏覽:559
php地址欄加密 瀏覽:167
手機app怎麼卸載電話卡 瀏覽:642
安卓文件斷點怎麼上傳 瀏覽:670
編譯器開根號怎麼寫 瀏覽:225
java指定字元串替換 瀏覽:988
東莞雲伺服器特價 瀏覽:909
java文件讀取大文件內容 瀏覽:979
雲牆美國伺服器地址 瀏覽:110
python形參是二維列表 瀏覽:828
程序員額外收入 瀏覽:202
java正則表達式d 瀏覽:38
潘承洞初等數論答案pdf 瀏覽:828
安全網路加密方式 瀏覽:76
linux命令目錄拼接當前日期 瀏覽:369
手機java程序運行 瀏覽:489
php或與非 瀏覽:423