java中多种方式读文件
一、多种方式读文件内容。
1、按字节读取文件内容 InputStream 读取的是字节
2、按字符读取文件内容 InputStreamReader 读取的是字符
3、按行读取文件内容 BufferredReader 可以读取行
4、随机读取文件内容
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
* @param fileName 文件的名
*/
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) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
* @param fileName 文件名
*/
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下,rn这两个字符在一起时,表示一个换行。
//但如果这两个字符分开显示时,会换两次行。
//因此,屏蔽掉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) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
* @param fileName 文件名
*/
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) {
}
}
}
}
/**
* 随机读取文件内容
* @param fileName 文件名
*/
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) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
* @param in
*/
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);
}
}
二、将内容追加到文件尾部
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* 将内容追加到文件尾部
*/
public class AppendToFile {
/**
* A方法追加文件:使用RandomAccessFile
* @param fileName 文件名
* @param content 追加的内容
*/
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
* @param fileName
* @param content
*/
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);
}
JAVA里常用的对文件流的读与写
用读配置文件来举例:
FileReader fread; String[] Get=new String[200]; fread=new FileReader("配置文件名"); Line=buff.readLine();//从文件读取一行字符串 …… buff.close(); |
用写日志文件的一个类来举例:
import java.io.*; public class CDbLog File fileobj = new File(LOGPATH+LOGFILE);
|
1) 输入输出流(程序从某个地方数据,程序将数据保存到某个地方)
输入流是将数据从数据源传送到程序,输出流是将数据从程序送到期望的地方。(什么是数据源是关键,不要混淆输入和输出)
字节:InputStream和OutputStream
双字节:Reader和Writer
Reader和Writer用于读取双字节的Unicode的字符,读取中文时不会出现乱码
类的层次,继承关系,这里主要介绍文件的读写,即子类FileInputStream等。
2) 标准输入输出流
System.in 接受用户在标准io设备上的输入,一般是键盘。
System.out
System.err
3) 流的常用方法
以上四个流的常用方法。
读取文件的操作:
数据源是文件,程序从文件里要数据,应该用输入流。
InputStream使用在二进制文件上,比如应用程序,图片,媒体文件等,Reader用在文本文件,比如log文件,txt文件等。
InputStream的子类FileInputStream的构造方法
构造方法摘要 | |
FileInputStream(File file) | |
FileInputStream(FileDescriptor fdObj) | |
FileInputStream(String name) |
Reader子类InputStreamReader的构造方法
构造方法摘要 | |
InputStreamReader(InputStream in) | |
InputStreamReader(InputStream in, Charset cs) | |
InputStreamReader(InputStream in, CharsetDecoder dec) | |
InputStreamReader(InputStream in, String charsetName) |
二者使用上的差异(inputstream读取unicode中文文件会产生乱码,见代码文件,略)
将内容保存到文件的操作
OutputStream和Writer类。
ReadFile.java
package FileOperation;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
//比较InputStream和Reader读txt文件,据说InputStream会产生乱码,但兵马俑。不知道为什么
public class ReadFile {
public static void main(String[] args) throws IOException {
if(args == null || args.length < 1)
{
System.out.println("缺少参数字符串给出要读取的文件的位置");
}
//传入一个参数指定文件位置
File file = new File(args[0]);
//调用readFileUsingInputStream(file)方法读取件
System.out.println("使用 InputStream 读取文件 " + file.getAbsolutePath() +
", 内容为: ");
System.out.println(readFileUsingInputStream(file));
//调用readFileUsingReader(file)读文件
System.out.println("使用 Reader 读取文件 " + file.getAbsolutePath() +
", 内容为: ");
System.out.println(readFileUsingReader(file));
}
/*用InputStream流读文件,注意这里抛出了异常,可能出现在ins.close();当你在方法内部
* 写到某个语句可能产生异常的时候,会有提示你在方法头声明异常,我们也可以看到throws出
* 的异常也并不一定要急着去处理,在main方法里调用此方法时再次把异常往上抛,并没有去处理*/
public static String readFileUsingInputStream(File file) throws IOException
{
InputStream ins = null;
StringBuffer buffer = new StringBuffer();//用一个buffer保存读取的数据
try{
ins = new FileInputStream(file);//FileInputStream的构造方法,指定某个文件
byte[] tmp = new byte[10];
int length = 0;
//int read(byte[] a)方法,从输入流读取数据,并存储于缓冲区a内,返回值为读取字节数
//流读取最后完好的保存了换行 空格
while((length = ins.read(tmp)) != -1)//每次读10字节
{
buffer.append(new String(tmp,0,length));
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(ins != null)
{
ins.close();
}
}
return buffer.toString();
}
//同上
public static String readFileUsingReader(File file) throws IOException
{
Reader reader = null;
StringBuffer buffer = new StringBuffer();
try{
reader = new InputStreamReader(new FileInputStream(file));
char[] tmp = new char[10];//字符流,注意跟上面的缓冲区的区别
int length = 0;
while((length = reader.read(tmp)) != -1)
{
buffer.append(new String(tmp,0,length));
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(reader != null)
{
reader.close();
}
}
return buffer.toString();
}
}
使用 InputStream 读取文件 D:\filetest.txt, 内容为:
标题:静夜思
作者:李白
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
使用 Reader 读取文件 D:\filetest.txt, 内容为:
标题:静夜思
作者:李白
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
WriteFile
package FileOperation;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
public class WriteFile {
public static void writeFileUsingOutputStream(File file,String content) throws Throwable
{
if(file.createNewFile())
System.out.println("已建立新文件 " + file.getAbsolutePath());
OutputStream ous = null;
try{
ous = new FileOutputStream(file);
ous.write(content.getBytes());
ous.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if(ous != null)
ous.close();
}
System.out.println("已写入文件 " + file.getAbsolutePath());
}
public static void writeFileUsingWriter(File file,String content) throws IOException
{
if(file.createNewFile())
System.out.println("已建立新文件 " + file.getAbsolutePath());
Writer writer = null;
try{
//注意writer的生成,由中间过程FileOutputStream转化了一次
writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write(content);
writer.flush();//强制将缓存里的数据输出
}catch(Exception e){
e.printStackTrace();
}finally{
if(writer != null)
writer.close();
}
System.out.println("已写入文件 " + file.getAbsolutePath());
}
public static void main(String[] args) throws Throwable {
System.out.println("请输入文件内容,#符号结束输入:");
//注意writer和reader对象都要通过另一个流生成
Reader reader = new InputStreamReader(System.in);//注意标准输入的用法
StringBuffer buffer = new StringBuffer();
char ch;
//输入内容都放入buffer里
while((ch = (char) reader.read()) != '#')
buffer.append(ch);
//分别用两种方法来保存内容
writeFileUsingOutputStream(new File("C:\\output_stream.txt"), buffer.toString());
writeFileUsingWriter(new File("C:\\ouput_writer.txt"),buffer.toString());
}
}
请输入文件内容,#符号结束输入:
标题:茕茕白兔
选自:诗经
茕茕白兔,
东奔西顾。
衣不如新,
人不如故。
#
已建立新文件 C:\output_stream.txt
已写入文件 C:\output_stream.txt
已建立新文件 C:\ouput_writer.txt
已写入文件 C:\ouput_writer.txt