`
坏我一锅粥
  • 浏览: 61420 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

11、java读取文件的几种方式

    博客分类:
  • IO
阅读更多
package com.tij.io.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;

/**
 * 读取文件
 * @author guoyoujun
 * @date 2014-3-17
 */
public class JavaReadFile {

	/**
	 * 工作中涉及到文件的时候,有时候我们需要读取阅读它, 现在提供几种不同的方式去读取;
	 * <p>java.nio.file.Files:这是java7中使用的类库,这个类可以读取所有的内容到数组或者读取所有的行到一个列表
	 * <p>java.io.FileReader:可以通过FileReader得到BufferRead从而读取文件的每一行,不过FileReader不支持格式编码所以并不是一种好的方式
	 * <p>java.io.BufferedReader:这是个很好的处理文件读取的类,支持编码、线程安全、默认缓存为8KB
	 * <p>java.util.Scanner:使用这个扫描类可以根据一些正则表达式来读取相应的内容, 默认的是分割内容是空白,是不同步的非线程安全的类
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		String fileName = "/Users/GYJ/webdefault.xml";
		readUsingFileReader(fileName);
		System.out.println("\n");
		readUsingBufferedReader(fileName);
		System.out.println("\n");
		readUsingBufferedReader(fileName, StandardCharsets.UTF_8);
		System.out.println("\n");
		readUsingBufferedReaderJava7(fileName, StandardCharsets.UTF_8);
		System.out.println("\n");
		readUsingFiles(fileName);
		System.out.println("\n");
		readUsingScanner(fileName);
		
	}
	
	/**
	 * FileReader读取
	 * @param fileName
	 * @throws IOException
	 */
	private static void readUsingFileReader(String fileName) throws IOException {
		File file = new File(fileName);
		FileReader fr = new FileReader(file);
		BufferedReader br = new BufferedReader(fr);
		String line;
		while ((line = br.readLine()) != null) {
			System.out.println("read result = " + line);
		}
		br.close();
		fr.close();
	}
	
	/**
	 * BufferedReader读取(支持编码格式)
	 * @param fileName
	 * @param charsetName
	 * @throws IOException
	 */
	private static void readUsingBufferedReader(String fileName, Charset cs) throws IOException  {
		File file = new File(fileName);
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis, cs);
		BufferedReader br = new BufferedReader(isr);
		String line;
		while ((line = br.readLine()) != null) {
			System.out.println("read result = " + line);
		}
		br.close();
	}
	
	/**
	 * BufferedReaderd读取文件
	 * @param fileName
	 * @param cs
	 * @throws IOException 
	 */
	private static void readUsingBufferedReaderJava7(String fileName, Charset cs) throws IOException {
		Path path = Paths.get(fileName);
        BufferedReader br = Files.newBufferedReader(path, cs);
        String line;
        while((line = br.readLine()) != null){
            System.out.println("read result = " + line);
        }
        br.close();
	}
	
	/**
	 * BufferedReader读取
	 * @param fileName
	 * @throws IOException
	 */
	private static void readUsingBufferedReader(String fileName) throws IOException {
		File file = new File(fileName);
		FileReader fr = new FileReader(file);
		BufferedReader br = new BufferedReader(fr);
		String line;
		while ((line = br.readLine()) != null) {
			System.out.println("read result = " + line);
		}
		br.close();
		fr.close();
	}
	
	/**
	 * 扫描读取文件
	 * @param fileNme
	 * @throws IOException 
	 */
	private static void readUsingScanner(String fileName) throws IOException {
		Path path = Paths.get(fileName);
        Scanner scanner = new Scanner(path);
        while(scanner.hasNextLine()){
            String line = scanner.nextLine();
            System.out.println("read result = " + line);
        }
	}
	
	/**
	 * 读取文件
	 * @param fileName
	 * @throws IOException
	 */
	private static void readUsingFiles(String fileName) throws IOException {
        Path path = Paths.get(fileName);
        byte[] bytes = Files.readAllBytes(path);
        List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
        System.out.println(bytes.length);
        System.out.println(allLines.size());
    }
	
}


//因为读取的是同一份文件输出结果就给出一遍的输出结果;
out put============
read result =   <!--                       dumped to a file? [false]                      -->
read result =   <!--                       False if suppressSmap is true                  -->
read result =   <!--                                                                      -->
read result =   <!--   scratchdir          What scratch directory should we use when      -->
read result =   <!--                       compiling JSP pages?  [default work directory  -->
read result =   <!--                       for the current web application]               -->
read result =   <!--                                                                      -->
read result =   <!--   tagpoolMaxSize      The maximum tag handler pool size  [5]         -->
read result =   <!--                                                                      -->
read result =   <!--   xpoweredBy          Determines whether X-Powered-By response       -->
read result =   <!--                       header is added by generated servlet  [false]  -->
read result =   <!--                                                                      -->
read result =   <!-- If you wish to use Jikes to compile JSP pages:                       -->
read result =   <!--   Set the init parameter "compiler" to "jikes".  Define              -->
read result =   <!--   the property "-Dbuild.compiler.emacs=true" when starting Jetty     -->
read result =   <!--   to cause Jikes to emit error messages in a format compatible with  -->
read result =   <!--   Jasper.                                                            -->
read result =   <!--   If you get an error reporting that jikes can't use UTF-8 encoding, -->
read result =   <!--   try setting the init parameter "javaEncoding" to "ISO-8859-1".     -->
read result =   <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
read result =   <servlet
read result =     id="jsp"
read result =   >
read result =     <servlet-name>jsp</servlet-name>
read result =     <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
read result =     <init-param>
read result =       <param-name>logVerbosityLevel</param-name>
read result =       <param-value>DEBUG</param-value>
read result =     </init-param>
read result =     <init-param>
read result =       <param-name>fork</param-name>
read result =       <param-value>false</param-value>
read result =     </init-param>
read result =     <init-param>
read result =       <param-name>xpoweredBy</param-name>
read result =       <param-value>false</param-value>
read result =     </init-param>
read result =     <!-- 
read result =     <init-param>
read result =         <param-name>classpath</param-name>
read result =         <param-value>?</param-value>
read result =     </init-param>
read result =     -->
read result =     <load-on-startup>0</load-on-startup>
read result =   </servlet>
read result =
read result =   <servlet-mapping>
read result =     <servlet-name>jsp</servlet-name>
read result =     <url-pattern>*.jsp</url-pattern>
read result =     <url-pattern>*.jspf</url-pattern>
read result =     <url-pattern>*.jspx</url-pattern>
read result =     <url-pattern>*.xsp</url-pattern>
read result =     <url-pattern>*.JSP</url-pattern>
read result =     <url-pattern>*.JSPF</url-pattern>
read result =     <url-pattern>*.JSPX</url-pattern>
read result =     <url-pattern>*.XSP</url-pattern>
read result =   </servlet-mapping>
read result =
read result =   <!-- ==================================================================== -->
read result =   <!-- Dynamic Servlet Invoker.                                             -->
read result =   <!-- This servlet invokes anonymous servlets that have not been defined   -->
read result =   <!-- in the web.xml or by other means. The first element of the pathInfo  -->
read result =   <!-- of a request passed to the envoker is treated as a servlet name for  -->
read result =   <!-- an existing servlet, or as a class name of a new servlet.            -->
read result =   <!-- This servlet is normally mapped to /servlet/*                        -->
read result =   <!-- This servlet support the following initParams:                       -->
read result =   <!--                                                                      -->
read result =   <!--  nonContextServlets       If false, the invoker can only load        -->
read result =   <!--                           servlets from the contexts classloader.    -->
read result =   <!--                           This is false by default and setting this  -->
read result =   <!--                           to true may have security implications.    -->
read result =   <!--                                                                      -->
read result =   <!--  verbose                  If true, log dynamic loads                 -->
read result =   <!--                                                                      -->
read result =   <!--  *                        All other parameters are copied to the     -->
read result =   <!--                           each dynamic servlet as init parameters    -->
read result =   <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
read result =   <!--
read result =     Uncomment for dynamic invocation <servlet> <servlet-name>invoker</servlet-name> <servlet-class>org.eclipse.jetty.servlet.Invoker</servlet-class> <init-param> <param-name>verbose</param-name>
read result =     <param-value>false</param-value> </init-param> <init-param> <param-name>nonContextServlets</param-name> <param-value>false</param-value> </init-param> <init-param>
read result =     <param-name>dynamicParam</param-name> <param-value>anyValue</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>invoker</servlet-name>
read result =     <url-pattern>/servlet/*</url-pattern> </servlet-mapping>
read result =   -->
read result =
read result =
read result =
read result =   <!-- ==================================================================== -->
read result =   <session-config>
read result =     <session-timeout>30</session-timeout>
read result =   </session-config>
read result =
read result =   <!-- ==================================================================== -->
read result =   <!-- Default MIME mappings                                                -->
read result =   <!-- The default MIME mappings are provided by the mime.properties        -->
read result =   <!-- resource in the org.eclipse.jetty.server.jar file.  Additional or modified  -->
read result =   <!-- mappings may be specified here                                       -->
read result =   <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
read result =   <!-- UNCOMMENT TO ACTIVATE
read result =   <mime-mapping>
read result =     <extension>mysuffix</extension>
read result =     <mime-type>mymime/type</mime-type>
read result =   </mime-mapping>
read result =   -->
read result =
read result =   <!-- ==================================================================== -->
read result =   <welcome-file-list>
read result =     <welcome-file>index.html</welcome-file>
read result =     <welcome-file>index.htm</welcome-file>
read result =     <welcome-file>index.jsp</welcome-file>
read result =   </welcome-file-list>
read result =
read result =   <!-- ==================================================================== -->
read result =   <locale-encoding-mapping-list>
read result =     <locale-encoding-mapping>
read result =       <locale>ar</locale>
read result =       <encoding>ISO-8859-6</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>be</locale>
read result =       <encoding>ISO-8859-5</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>bg</locale>
read result =       <encoding>ISO-8859-5</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>ca</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>cs</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>da</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>de</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>el</locale>
read result =       <encoding>ISO-8859-7</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>en</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>es</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>et</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>fi</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>fr</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>hr</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>hu</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>is</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>it</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>iw</locale>
read result =       <encoding>ISO-8859-8</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>ja</locale>
read result =       <encoding>Shift_JIS</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>ko</locale>
read result =       <encoding>EUC-KR</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>lt</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>lv</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>mk</locale>
read result =       <encoding>ISO-8859-5</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>nl</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>no</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>pl</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>pt</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>ro</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>ru</locale>
read result =       <encoding>ISO-8859-5</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>sh</locale>
read result =       <encoding>ISO-8859-5</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>sk</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>sl</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>sq</locale>
read result =       <encoding>ISO-8859-2</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>sr</locale>
read result =       <encoding>ISO-8859-5</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>sv</locale>
read result =       <encoding>ISO-8859-1</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>tr</locale>
read result =       <encoding>ISO-8859-9</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>uk</locale>
read result =       <encoding>ISO-8859-5</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>zh</locale>
read result =       <encoding>GB2312</encoding>
read result =     </locale-encoding-mapping>
read result =     <locale-encoding-mapping>
read result =       <locale>zh_TW</locale>
read result =       <encoding>Big5</encoding>
read result =     </locale-encoding-mapping>
read result =   </locale-encoding-mapping-list>
read result =
read result =   <security-constraint>
read result =     <web-resource-collection>
read result =       <web-resource-name>Disable TRACE</web-resource-name>
read result =       <url-pattern>/</url-pattern>
read result =       <http-method>TRACE</http-method>
read result =     </web-resource-collection>
read result =     <auth-constraint/>
read result =   </security-constraint>
read result =
read result = </web-app>
read result =
=====================================================================
使用哪一种方式去读取文件取决于项目需求,希望能用到的同学自己决定;
分享到:
评论

相关推荐

    Java文件下载的几种方式

    ### Java文件下载的几种方式详解 在Java编程中,文件下载是常见的操作之一,无论是从本地文件系统还是网络上下载文件,都需要掌握一定的技巧和方法。本文将详细介绍几种常用的Java文件下载方式,包括本地文件下载、...

    Java读取文件的几种方式

    介绍Java直接读取、带缓冲读取、内存映射读取文件,并详细注释。

    java读取配置文件

    在Java中,我们可以使用多种方法来读取配置文件,下面将详细介绍几种常见的方法。 1. **使用`java.io`流读取** 最基础的方式是使用Java的I/O流来读取文本配置文件(通常是.properties格式)。例如,`java.io....

    使用Java实现对dbf文件的简单读写

    使用 Java 实现对 dbf 文件的简单读写需要使用以下几个类: 1. DBFWriter:用于 dbf 文件的写操作,提供了写入 dbf 文件的方法。 2. JDBField:用于表示 dbf 文件中的字段信息,包括字段名、字段类型、字段长度等。...

    hdf5文件结构以及基于java的读写

    ### HDF5 文件结构以及基于 Java 的读写 #### HDF 概述 HDF(Hierarchical Data Format)是一种自我描述、多对象的文件格式,专为高效地存储和分发科学数据而设计。它由美国国家超级计算应用中心(NCSA)开发,...

    java下载文件的种方式

    这篇博客"java下载文件的种方式"可能详细介绍了几种不同的Java实现文件下载的方法。以下是对这些方法的总结和扩展: 1. **HTTP响应流下载** 这是最基本的方式,通过Servlet或Spring MVC等框架处理HTTP请求,然后在...

    java读写xml文件

    ### Java读写XML文件知识点详解 #### 一、概述 在Java编程中,对XML文件进行读取与写入是一项非常常见的任务。XML(可扩展标记语言)是一种用于标记数据的语言,非常适合用来存储和传输数据。Java提供了多种API来...

    java读取.properties配置文件的几种方法

    下面将详细介绍几种在Java中读取`.properties`配置文件的方法。 1. 使用`java.util.Properties`类 `Properties`类是Java提供的一种内置机制,用于处理属性列表。它继承了`Hashtable`类,提供了加载和保存属性列表...

    Java流(文件读写操作)

    ### Java流(文件读写操作) ...这些示例展示了如何使用Java流读取文件的不同方式。通过这些基本的示例,开发者可以更好地理解Java流的工作原理,并能够根据具体需求选择合适的流类型进行文件读写操作。

    Java读取TXT文本文件乱码解决方案.doc

    "Java读取TXT文本文件乱码解决方案" Java 读取 TXT 文本文件乱码解决方案中,主要讨论的是在 Java 中读取 TXT 文本文件时出现乱码的问题,并提供了解决方案。 首先,文章中提供了一个简单的读取 TXT 文件的代码,...

    JAVA读写文件小实例

    首先,我们需要理解Java中的几个关键类,如`java.io.File`、`java.io.FileReader`、`java.io.FileWriter`、`java.io.BufferedReader`和`java.io.BufferedWriter`,它们在文件操作中起着核心作用。 `File`类是Java中...

    用java读取修改xml文件的代码实现

    本文将详细介绍如何使用Java来读取和修改XML文件,主要涉及以下几个核心知识点: 1. **DOM解析器**: Document Object Model(DOM)是一种将XML文档转换为内存中的树形结构的方法,使得可以遍历和修改XML文件。...

    java读写文件的集中方式

    本文将详细介绍几种常见的Java文件读写方式,包括按行读取和写入、随机读取以及按字节读取。 1. **按行读取和写入** 在Java中,我们可以使用`BufferedReader`和`PrintWriter`类来实现按行读取和写入文件。`...

    java 读取properties文件代码

    在Java编程中,Properties文件是一种常用的配置文件格式,用于存储应用程序的配置参数或者环境设置。这些文件通常以键值对的形式存在,例如`key=value`。读取Properties文件是Java开发中的常见操作,特别是在需要...

    JAVA简单的读写文本文件的代码

    通过上述四个主要部分的分析,我们可以看到Java语言在处理文件读写方面提供了丰富的API支持。使用合适的类库可以极大地简化开发工作并提高程序的性能。例如,使用`StringBuffer`可以有效地处理字符串的动态增长;而`...

    java读取文件方法大全.txt

    ### Java读取文件方法概述 在Java中,有多种方式可以用来读取文件的内容。这些方法大致可以分为两类:基于字节流的方法和基于字符流的方法。这两种方法分别适用于不同的场景,具体选择哪一种取决于实际需求。 ####...

    java读取kml文件数据

    Java语言在处理各种类型的数据文件方面具有广泛的应用,其中之一就是读取KML(Keyhole Markup Language)文件。KML是一种用于存储地理空间数据的标准格式,常用于Google Earth、Google Maps等应用。本项目的核心是...

    JAVA读取文件——以行为单位读取

    在Java编程语言中,读取文件是常见的任务之一,尤其对于处理文本文件,如TXT文件,以行为单位读取文件内容是一种效率较高且易于管理数据的方式。本篇将深入探讨如何使用Java进行逐行读取TXT文件,并提供相关示例代码...

Global site tag (gtag.js) - Google Analytics