Java的I/O
1.基于字节操作的I/O接口:InputStream和OutputStream
2.基于字符操作的I/O接口:Writer和Reader
3.基于磁盘操作的I/O接口:File
1) 字节流和字符流的区别:
字节流和字符流的区别在于字符流在写入文件的过程中会先在缓存区缓存,而字节流则是直接操作文件。字符流只有在流关闭时才会写入文件,另外,当使用flush时也可以强制将缓存区内容写入文件。
2) 所有的文件在硬盘或在传输时都是以字节的方式进行的,包括图片等都是按字节的方式存储的,而字符是只有在内存中才会形参,所有在开发中,字节流使用较为广泛。
3) 按照java IO流的方向可以分为输入流和输出流。输入流是将数据写入缓冲Buffer,输出流是将缓冲Buffer中的数据输出到某文件。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
public class InputStreamTest {
static String path = "src/com/cn/llj/ios/InputStreamTest.java";
//static String path2 = "E:\\My Data/My essay/111110.doc";//这两种方法输出到控制台都是乱码。
//static String path3 = "E:\\My Data/My essay/111111.doc";//没有乱码
//static String path4 = "E:\\My Data/My essay/111112.doc";//全部乱码
static String path2 = "E:\\My Data/My essay/0.txt";//两个文档都是全中文,验证中文的乱码问题。
static String path3 = "E:\\My Data/My essay/1.txt";//没有乱码,无论哪种编码方式
static String path4 = "E:\\My Data/My essay/2.txt";//当java文件使用GBK编码时,没有乱码;使用UTF-8编码时,乱码
/**
* 使用FileInputStream读取该类本身
* */
public static void FileInputStreamTest() throws Exception{
FileInputStream fis = null;
FileOutputStream fos = null;
try{
//创建字节输入流
fis = new FileInputStream(path2);
fos = new FileOutputStream(path3);
//创建一个长度为1024的字节数组来存取
byte[] bbuf = new byte[1024];
int num = 0;
//用于保存实际读取的字节数
int hasRead = 0;
//使用循环来进行重复读取
while((hasRead = fis.read(bbuf))> 0){
//取出字节,将字节数组转化为字符串输出
// System.out.println(new String(bbuf, 0 , hasRead));
fos.write(bbuf, 0 , hasRead);
num = num + hasRead;
}
System.out.println("num === "+num);
}finally{
//关闭文件输入流
fis.close();
fos.close();
}
}
/**
* 使用FileReader读取该类本身
* */
public static void FileReaderTest() throws Exception{
FileReader fr = null;
FileWriter fw = null;
try{
//创建字符输入流
fr = new FileReader(path2);
fw = new FileWriter(path4);
//创建一个长度为40的字符数组来存取
char[] bbuf = new char[40];
int num = 0;
//用于保存实际读取的字符数
int hasRead = 0;
//使用循环来进行重复读取
while((hasRead = fr.read(bbuf))> 0){
//取出字节,将字节数组转化为字符串输出
// System.out.println(new String(bbuf, 0 , hasRead));
fw.write(bbuf, 0 , hasRead);
num = num + hasRead;
}
System.out.println("num ===------ "+num);
}finally{
//关闭文件输入流
fr.close();
fw.close();
}
}
public static void main(String[] args) throws Exception{
InputStreamTest.FileInputStreamTest();
InputStreamTest.FileReaderTest();
}
}