导航:首页 > 编程语言 > 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
东莞云服务器特价 浏览:908
java文件读取大文件内容 浏览:978
云墙美国服务器地址 浏览:109
python形参是二维列表 浏览:828
程序员额外收入 浏览:202
java正则表达式d 浏览:38
潘承洞初等数论答案pdf 浏览:828
安全网络加密方式 浏览:76
linux命令目录拼接当前日期 浏览:369
手机java程序运行 浏览:489
php或与非 浏览:423