文件管理 · 2022年8月24日

文件读取java|java中如何从文件中读取数据

A. java 如何读取大文件

以下将从常规方法谈起,通过对比来说明应该如何使用java读取大文件。1、常规:在内存中读取读取文件行的标准方式是在内存中读取,Guava 和Apache Commons IO都提供了如下所示快速读取文件行的方法:Files.readLines(new File(path), Charsets.UTF_8);FileUtils.readLines(new File(path));这种方法带来的问题是文件的所有行都被存放在内存中,当文件足够大时很快就会导致程序抛出OutOfMemoryError 异常。例如:读取一个大约1G的文件: @Testpublic 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内存)

B. java中如何从文件中读取数据

分为读字节,读字符两种读法◎◎◎FileInputStream 字节输入流读文件◎◎◎public class Maintest { public static void main(String[] args) throws IOException { File f=new File("G:\\just for fun\\xiangwei.txt"); FileInputStream fin=new FileInputStream(f); byte[] bs=new byte[1024]; int count=0; while((count=fin.read(bs))>0) { String str=new String(bs,0,count); //反复定义新变量:每一次都 重新定义新变量,接收新读取的数据 System.out.println(str); //反复输出新变量:每一次都 输出重新定义的新变量 }fin.close(); }}◎◎◎FileReader 字符输入流读文件◎◎◎public class Maintest { public static void main(String[] args) throws IOException { File f=new File("H:\\just for fun\\xiangwei.txt"); FileReader fre=new FileReader(f); BufferedReader bre=new BufferedReader(fre); String str=""; while((str=bre.readLine())!=null) //●判断最后一行不存在,为空 { System.out.println(str); } bre.close(); fre.close(); } }

C. java 如何读写文件

public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 */ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while ((tempbyte = in.read()) != -1) { System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); // 一次读多个字节 byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(fileName); ReadFromFile.showAvailableBytes(in); // 读入多个字节到字节数组中,byteread为一次读入的字节数 while ((byteread = in.read(tempbytes)) != -1) { System.out.write(tempbytes, 0, byteread); } } catch (Exception e1) { e1.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e1) { } } } } /** * 以字符为单位读取文件,常用于读文本,数字等类型的文件 */ public static void readFileByChars(String fileName) { File file = new File(fileName); Reader reader = null; try { System.out.println("以字符为单位读取文件内容,一次读一个字节:"); // 一次读一个字符 reader = new InputStreamReader(new FileInputStream(file)); int tempchar; while ((tempchar = reader.read()) != -1) { // 对于windows下,\r\n这两个字符在一起时,表示一个换行。 // 但如果这两个字符分开显示时,会换两次行。 // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。 if (((char) tempchar) != '\r') { System.out.print((char) tempchar); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } try { System.out.println("以字符为单位读取文件内容,一次读多个字节:"); // 一次读多个字符 char[] tempchars = new char[30]; int charread = 0; reader = new InputStreamReader(new FileInputStream(fileName)); // 读入多个字符到字符数组中,charread为一次读取字符数 while ((charread = reader.read(tempchars)) != -1) { // 同样屏蔽掉\r不显示 if ((charread == tempchars.length) && (tempchars[tempchars.length – 1] != '\r')) { System.out.print(tempchars); } else { for (int i = 0; i < charread; i++) { if (tempchars[i] == '\r') { continue; } else { System.out.print(tempchars[i]); } } } } } catch (Exception e1) { e1.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } /** * 以行为单位读取文件,常用于读面向行的格式化文件 */ public static void readFileByLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } /** * 随机读取文件内容 */ public static void readFileByRandomAccess(String fileName) { RandomAccessFile randomFile = null; try { System.out.println("随机读取一段文件内容:"); // 打开一个随机访问文件流,按只读方式 randomFile = new RandomAccessFile(fileName, "r"); // 文件长度,字节数 long fileLength = randomFile.length(); // 读文件的起始位置 int beginIndex = (fileLength > 4) ? 4 : 0; // 将读文件的开始位置移到beginIndex位置。 randomFile.seek(beginIndex); byte[] bytes = new byte[10]; int byteread = 0; // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。 // 将一次读取的字节数赋给byteread while ((byteread = randomFile.read(bytes)) != -1) { System.out.write(bytes, 0, byteread); } } catch (IOException e) { e.printStackTrace(); } finally { if (randomFile != null) { try { randomFile.close(); } catch (IOException e1) { } } } } /** * 显示输入流中还剩的字节数 */ private static void showAvailableBytes(InputStream in) { try { System.out.println("当前字节输入流中的字节数为:" + in.available()); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; ReadFromFile.readFileByBytes(fileName); ReadFromFile.readFileByChars(fileName); ReadFromFile.readFileByLines(fileName); ReadFromFile.readFileByRandomAccess(fileName); }}复制代码5、将内容追加到文件尾部public class AppendToFile { /** * A方法追加文件:使用RandomAccessFile */ public static void appendMethodA(String fileName, String content) { try { // 打开一个随机访问文件流,按读写方式 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); // 文件长度,字节数 long fileLength = randomFile.length(); //将写文件指针移到文件尾。 randomFile.seek(fileLength); randomFile.writeBytes(content); randomFile.close(); } catch (IOException e) { e.printStackTrace(); } } /** * B方法追加文件:使用FileWriter */ public static void appendMethodB(String fileName, String content) { try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 FileWriter writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; String content = "new append!"; //按方法A追加文件 AppendToFile.appendMethodA(fileName, content); AppendToFile.appendMethodA(fileName, "append end. \n"); //显示文件内容 ReadFromFile.readFileByLines(fileName); //按方法B追加文件 AppendToFile.appendMethodB(fileName, content); AppendToFile.appendMethodB(fileName, "append end. \n"); //显示文件内容 ReadFromFile.readFileByLines(fileName); }}

D. java文件如何读取

有几种方法读取吧Filefile=newFile("d:\\a.txt");//把D盘目录下的a.txt读取出来,InputStreamis=newFileInputStream(file);//把文件以字节流读到内存中第二种是类加载Demo1.class.getClassLoader().getResourceAsStream("a.txt");//Demo1为当前类名,a.txt在与Demo1.class在同一目录下。还有其它的就不说了

E. Java文件读写

实用的模糊(通配符)文件查找程序1 import java.io.File; 2 import java.util.regex.Matcher; 3 import java.util.regex.Pattern; 4 import java.util.ArrayList; 5 6 /** *//** 7 * <p>Title: FileService </p> 8* <p>Description: 获取文件 </p> 9* <p>Copyright: Copyright (c) 2007</p>10* <p>Company: </p>11* @author not attributable12* @version 1.013*/14public class FileService {15 public FileService() {16 }1718 /** *//**19 * 在本文件夹下查找20 * @param s String 文件名21 * @return File[] 找到的文件22 */23 public static File[] getFiles(String s)24 {25 return getFiles("./",s);26 }27 28 /** *//**29 * 获取文件30 * 可以根据正则表达式查找31 * @param dir String 文件夹名称32 * @param s String 查找文件名,可带*.?进行模糊查询33 * @return File[] 找到的文件34 */35 public static File[] getFiles(String dir,String s) {36 //开始的文件夹37 File file = new File(dir);3839 s = s.replace('.', '#');40 s = s.replaceAll("#", "\\\\.");

F. java如何读取txt文件

读取txt文件(一整个获取)

G. java中怎样从一个文件中读取文件信息

java读取文件路径、所占空间大小等文件消息,主要是使用FileInputStream类来操作,示例如内下:

importjava.io.File;importjava.io.FileInputStream;publicclassceshi{ publicstaticvoidmain(String[]args)throwsException{ 容java.io.FilelocalFile=newFile("D:\1.txt"); FileInputStreamins=newFileInputStream(localFile); intcountLen=ins.available(); byte[]m_binArray=newbyte[countLen]; ins.read(m_binArray); ins.close(); System.out.println(localFile.getAbsoluteFile()+"" +localFile.getFreeSpace()); }}

运行结果如下:

H. Java 如何读取txt文件的内容

能有的,很简单,readLine即可,然后封装到Map里面,key就是序号,value就是后面的值

I. JAVA中读取文件(二进制,字符)内容的几种方

JAVA中读取文件内容的方法有很多,比如按字节读取文件内容,按字符读取文件内容,按行读取文件内容,随机读取文件内容等方法,本文就以上方法的具体实现给出代码,需要的可以直接复制使用public class ReadFromFile {/*** 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。*/public static void readFileByBytes(String fileName) {File file = new File(fileName);InputStream in = null;try {System.out.println("以字节为单位读取文件内容,一次读一个字节:");// 一次读一个字节in = new FileInputStream(file);int tempbyte;while ((tempbyte = in.read()) != -1) {System.out.write(tempbyte);}in.close();} catch (IOException e) {e.printStackTrace();return;}try {System.out.println("以字节为单位读取文件内容,一次读多个字节:");// 一次读多个字节byte[] tempbytes = new byte[100];int byteread = 0;in = new FileInputStream(fileName);ReadFromFile.showAvailableBytes(in);// 读入多个字节到字节数组中,byteread为一次读入的字节数while ((byteread = in.read(tempbytes)) != -1) {System.out.write(tempbytes, 0, byteread);}} catch (Exception e1) {e1.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e1) {}}}}/*** 以字符为单位读取文件,常用于读文本,数字等类型的文件*/public static void readFileByChars(String fileName) {File file = new File(fileName);Reader reader = null;try {System.out.println("以字符为单位读取文件内容,一次读一个字节:");// 一次读一个字符reader = new InputStreamReader(new FileInputStream(file));int tempchar;while ((tempchar = reader.read()) != -1) {// 对于windows下,\r\n这两个字符在一起时,表示一个换行。// 但如果这两个字符分开显示时,会换两次行。// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。if (((char) tempchar) != '\r') {System.out.print((char) tempchar);}}reader.close();} catch (Exception e) {e.printStackTrace();}try {System.out.println("以字符为单位读取文件内容,一次读多个字节:");// 一次读多个字符char[] tempchars = new char[30];int charread = 0;reader = new InputStreamReader(new FileInputStream(fileName));// 读入多个字符到字符数组中,charread为一次读取字符数while ((charread = reader.read(tempchars)) != -1) {// 同样屏蔽掉\r不显示if ((charread == tempchars.length)&& (tempchars[tempchars.length – 1] != '\r')) {System.out.print(tempchars);} else {for (int i = 0; i < charread; i++) {if (tempchars[i] == '\r') {continue;} else {System.out.print(tempchars[i]);}}}}} catch (Exception e1) {e1.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e1) {}}}}/*** 以行为单位读取文件,常用于读面向行的格式化文件*/public static void readFileByLines(String fileName) {File file = new File(fileName);BufferedReader reader = null;try {System.out.println("以行为单位读取文件内容,一次读一整行:");reader = new BufferedReader(new FileReader(file));String tempString = null;int line = 1;// 一次读入一行,直到读入null为文件结束while ((tempString = reader.readLine()) != null) {// 显示行号System.out.println("line " + line + ": " + tempString);line++;}reader.close();} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e1) {}}}}/*** 随机读取文件内容*/public static void readFileByRandomAccess(String fileName) {RandomAccessFile randomFile = null;try {System.out.println("随机读取一段文件内容:");// 打开一个随机访问文件流,按只读方式randomFile = new RandomAccessFile(fileName, "r");// 文件长度,字节数long fileLength = randomFile.length();// 读文件的起始位置int beginIndex = (fileLength > 4) ? 4 : 0;// 将读文件的开始位置移到beginIndex位置。randomFile.seek(beginIndex);byte[] bytes = new byte[10];int byteread = 0;// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。// 将一次读取的字节数赋给bytereadwhile ((byteread = randomFile.read(bytes)) != -1) {System.out.write(bytes, 0, byteread);}} catch (IOException e) {e.printStackTrace();} finally {if (randomFile != null) {try {randomFile.close();} catch (IOException e1) {}}}}/*** 显示输入流中还剩的字节数*/private static void showAvailableBytes(InputStream in) {try {System.out.println("当前字节输入流中的字节数为:" + in.available());} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {String fileName = "C:/temp/newTemp.txt";ReadFromFile.readFileByBytes(fileName);ReadFromFile.readFileByChars(fileName);ReadFromFile.readFileByLines(fileName);ReadFromFile.readFileByRandomAccess(fileName);}}

J. java中文件的读取实现,以及用到哪些类

ava.io包中包括许多类提供许多有关文件的各个方面操作。1 输入输出抽象基类InputStream/OutputStream ,实现文件内容操作的基本功能函数read()、 write()、close()、skip()等;一般都是创建出其派生类对象(完成指定的特殊功能)来实现文件读写。在文件读写的编程过程中主要应该注意异常处理的技术。 2 FileInputStream/FileOutputStream: 用于本地文件读写(二进制格式读写并且是顺序读写,读和写要分别创建出不同的文件流对象); 本地文件读写编程的基本过程为: ① 生成文件流对象(对文件读操作时应该为FileInputStream类,而文件写应该为FileOutputStream类); ② 调用FileInputStream或FileOutputStream类中的功能函数如read()、write(int b)等)读写文件内容; ③ 关闭文件(close())。 3 PipedInputStream/PipedOutputStream: 用于管道输入输出(将一个程序或一个线程的输出结果直接连接到另一个程序或一个线程的输入端口,实现两者数据直接传送。操作时需要连结); 4管道的连接: 方法之一是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象 PipedInputStream pInput=new PipedInputStream(); PipedOutputStream pOutput= new PipedOutputStream(pInput); 方法之二是利用双方类中的任一个成员函数 connect()相连接 PipedInputStream pInput=new PipedInputStream(); PipedOutputStream pOutput= new PipedOutputStream(); pinput.connect(pOutput); 5 管道的输入与输出: 输出管道对象调用write()成员函数输出数据(即向管道的输入端发送数据);而输入管道对象调用read()成员函数可以读起数据(即从输出管道中获得数据)。这主要是借助系统所提供的缓冲机制来实现的。 6随机文件读写: RandomAccessFile类(它直接继承于Object类而非InputStream/OutputStream类),从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。 随机文件读写编程的基本过程为: ① 生成流对象并且指明读写类型; ② 移动读写位置; ③ 读写文件内容; ④ 关闭文件。