黑马程序员技术交流社区
标题:
常用的文件读取方法
[打印本页]
作者:
micro_hx
时间:
2015-6-13 16:53
标题:
常用的文件读取方法
由于刚刚初学java,很多都不懂,新手勿喷。。
下面是自己总结的几个文件读取的例子,都没有使用try catch,异常全都抛出了。。。
package com.test1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.Reader;
import org.junit.Test;
/**
* 各种读取文件的方式
* @author Administrator
*/
public class Test2 {
private final static String FILE_PATH = "D:/Test.java" ;
/**
* 使用的是read()方法, 使用的是其子类FileReader
* @throws Exception
*/
@Test
public void testReader() throws Exception {
Reader reader = new FileReader(new File(FILE_PATH));
int len = 0 ;
while((len = reader.read()) != -1){
System.out.print((char)len);
}
reader.close();
}
/**
* 使用是read(buf)方法,使用的是其子类FileReader
* @throws Exception
*/
@Test
public void testReader2()throws Exception{
Reader reader = new FileReader(new File(FILE_PATH));
char[] but = new char[1024];
int len = 0 ;
while((len=reader.read(but)) != -1){
System.out.println(new String(but,0,len));
}
reader.close();
}
/**
* 使用readLine()方法,该方法在读取效率中最高,因为是整行整行读取,
* 使用的是BufferedReader类
* @throws Exception
*/
@Test
public void testReader3()throws Exception{
BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_PATH)));
String len = null ;
while((len = reader.readLine()) != null){
System.out.println(len);
}
reader.close();
}
/**
*是read()方法,但是使用的是InputStream的子类FileInputStream
* @throws Exception
*/
@Test
public void testReader4() throws Exception{
InputStream input = new FileInputStream(new File(FILE_PATH));
int temp = 0 ;
while((temp = input.read()) != -1){
System.out.print((char)temp);
}
input.close();
}
/**
* 使用的是read(byte[]) 方法,使用的是InputStream的子类中的FileInputStream类
* @throws Exception
*/
@Test
public void testReader5() throws Exception{
InputStream input = new FileInputStream(new File(FILE_PATH));
byte[] but = new byte[1024];
int i = 0 ;
while((i = input.read(but)) != -1){
System.out.println(new String(but,0,i));
}
input.close();
}
}
复制代码
当然,方法远远不止这些,希望大神看到后,能补上自己的方法,大家相互交流,可能今后还要在同一个班学习了,这里先表态了啊。。。。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2