import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo {
/*
* 使用字节流处理字符
* UTF-8:万国码,汉字 3~4个字节
* GBK:汉字为2个字节
*/
public static void main(String[] args) {
String str = "今天天气sdfadfgadgfdagertdfgvafdhythgbdhghdytujythdghjgfjhjfhj!";
String path = "C:/Users/Desktop/c.txt";
writeChinese(str, path);
readChinese(path);
// deleteFile(path);
}
public static void writeChinese(String str,String path) {
File file = new File(path);
File parent = file.getParentFile();
FileOutputStream fos = null;
try{
if(!parent.exists()){
parent.mkdirs();
}
if(!file.exists()){
file.createNewFile();
}
//把文件传入字节输出流的构造方法
fos = new FileOutputStream(file);
/*
* 相当于使用系统默认的编码格式:gbk
* getBytes(String charasetName)
*/
byte[] b = str.getBytes("utf-8");
fos.write(b);
}catch(IOException e){
e.printStackTrace();
}finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//使用字节流读取文件的方法
public static void readChinese(String path) {
FileInputStream fis = null;
/*
* 字节流与字符流的桥梁:InputStreamReader
* new InputStreamReader(InputStream in,String charsetName)
*/
InputStreamReader isr =null;
try{
fis = new FileInputStream(path);
isr = new InputStreamReader(fis, "utf-8");
byte[] b = new byte[3];
int len = 0;
String str = "";
while((len = fis.read(b)) != -1){
String s = new String(b,0,len);
str += s;
}
System.out.println(str+"0");
// char[] c = new char[3];
// int len1 = 0;
// String str1 = "";
// while((len1 = isr.read(c)) != -1){
// String s = new String(c,0,len1);
// str1 += s;
// }
// System.out.println(str1+"1");
isr.close();
}catch(IOException e){
e.printStackTrace();
}finally {
if(isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void deleteFile(String path){
File file = new File(path);
if(file.exists()){
file.delete();
}
}
}
IO流:数据的传输。文件和程序之间进行数据交互。
I---->Input 输入
O---->Output 输出
流:类似水流。以先进先出的方式进行数据传输。
io中所有的类或异常来自java.io包
IO的四个基类(父类、超类):抽象类.
InputStream
OutputStream
Writer
Reader
1.按流向分:以内存为准分出输入和输出。
输入流:InputStream Reader
输出流:OutputStream Writer
读入 写出!
2.按传输单位划分:实际上在传输过程中,底层在使用二进制。
字节流:InputStream OutputStream
字符流: Reader Writer