Java IO文件读写有2种方式,分别是字节流和字符流。
读文件:
java.io.BufferedReader;//读文件到内存buffer中
java.io.FileInputStream;//字节流读取文件
java.io.FileReader;//字符流读取文件
java.io.InputStreamReader;//是字节流通向字符流的桥梁
写文件:
java.io.BufferedWriter;//将内存buffer中的文件写入到本地或其他地方
java.io.FileOutputStream;//字节流写文件
java.io.FileWriter;//字符流写文件
java.io.OutputStreamWriter;//是字符流通向字节流的桥梁
要想转换编码格式,目的就是读取字符流,但要通过字节流进行格式的转换,所以必须要用到InputStreamReader或者OutputStreamWriter的当桥梁:
eg: new InputStreamReader(in,”UTF-8”) // 指定读取文件时以UTF-8的格式读取
new OutputStreamWriter(out,”GB2312”) // 指定写入文件时以GB2312的格式写入
下面是文件读写的例子。
读文件例子代码:
package com.samples;
/**
* Java IO Read File.
*/
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 JavaIOReadFile {
/**
* 采用的是操作系统底层默认的编码方式,GBK等,非UTF8
*/
/**
* 以字节为单位读取文件内容,常用于读取二进制文件,比如图片、影像、声音等文件
*/
public static void readFileByBytes(String filename) {
File file = new File(filename);
FileInputStream in = null;
try {
System.out.println("以字节为单位读取文件,一次读一个字节: ");
in = new FileInputStream(file);
int temp = 0;
while ((temp = in.read()) != -1) {
System.out.println(temp);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件,一次读多个字节: ");
byte[] temp = new byte[100];//read the characters to the buffer temp.
int byteread = 0;
in = new FileInputStream(file);
JavaIOReadFile.showAvailableBytes(in);
while ((byteread = in.read(temp)) != -1) {
System.out.write(temp, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChar(String filename) {
File file = new File(filename);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次一个字节:");
// InputStreamReader类:是字节向字符转换的桥梁
reader = new InputStreamReader(new FileInputStream(file));
int temp;
while ((temp = reader.read()) != -1) {
if (((char) temp) != '\r') {
System.out.println((char) temp);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节: ");
char[] temp = new char[30];//read the characters to the buffer temp.
int charread = 0;
reader = new InputStreamReader(new FileInputStream(filename));
while ((charread = reader.read(temp)) != -1) {
if ((charread == temp.length) && (temp[temp.length - 1] != '\r')) {
System.out.println(temp);
} else {
for (int i = 0; i < charread; i++) {
if (temp[i] == '\r') {
break;
} else {
System.out.println(temp[i]);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLine(String filename) {
File file = new File(filename);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行: ");
reader = new BufferedReader(new FileReader(file));
String temp = null;
int line = 1;
while ((temp = reader.readLine()) != null) {
System.out.println("line " + line + ": " + temp);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
/**
* 随机读取文件内容
*/
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);
randomfile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
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 e) {
}
}
}
}
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 = "D:\\workspace\\HelloJava\\Files\\IOReadTest.txt";//绝对路径
String filename = "Files/IOReadTest.txt";//相对路径
JavaIOReadFile.readFileByBytes(filename);
JavaIOReadFile.readFileByChar(filename);
JavaIOReadFile.readFileByLine(filename);
JavaIOReadFile.readFileByRandomAccess(filename);
}
}
写文件例子代码:
package com.samples;
/**
* Java IO write file
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class JavaIOWriteFile {
public static void main(String[] args) throws IOException {
String Path="Files";
File file=new File("Files","IOWriteTest.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Java写入文件的三种方法
* */
FileOutputStream fos=null;
BufferedWriter bw=null;
FileWriter fw=null;
int value=1000;
try {
//write binary data
fos=new FileOutputStream(new File(Path+"/"+"fos.txt"));
long begin=System.currentTimeMillis();
for (int i=1; i<=value; i++) {
fos.write(5);
}
long end=System.currentTimeMillis();
System.out.println("TheCostTime of FileOutputStream is : " + (end-begin));
fos.close();
//write data to buffer
//OutputStreamWriter is the bridge between BufferedWriter and FileOutputStream
bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(Path+"/"+"br.txt")),"UTF8"));
begin=System.currentTimeMillis();
for (int i=1; i<=value; i++) {
bw.write(5);
bw.newLine();
}
bw.close();
end=System.currentTimeMillis();
System.out.println("TheCostTime of BufferedWriter is : " + (end-begin));
//write character
fw=new FileWriter(Path+"/"+"fw.txt");
begin=System.currentTimeMillis();
for (int i=1; i<=value; i++) {
fw.write(5);
}
fw.close();
end=System.currentTimeMillis();
System.out.println("TheCostTime of FileWriter is : " + (end-begin));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close(); //FileOutputStream
bw.close(); //BufferedWriter
fw.close(); //FileWriter
} catch (Exception e) {
e.printStackTrace();
}
}
}
}