IO流分为 字节流和字符流
* 或者读取流和写入流
* 或者输入流和输出流(内存)
字节流
字节码,如视频、音频(一个中文2字节,一个英文1字节)。
写入:字节数组[12,34,56,4]按照字节数组的顺序进行写入;
读取:读取时需要相应的编码转化字节数组;
ASCII –美国 GBK–中国 UTF–国际
普通流:与硬盘交互
InputStream(fileInputStream类) 字节输入流(对于内存来说是输入) 读取文件内容,(不说 读取 输出);
OutputStream;
高效流:与内存交互
BufferedInputStream
BufferedOutputStream
字符串转为字节数组:
public class test {
public static void main(String[] args) {
String s ="你好";
byte[] by = s.getBytes();
for(byte b:by) {
System.out.println(b);
}
String str = new String(by);
System.out.println(str);
}
}
字节输入流inputStream
|桥梁是 InputStreamReader
字符输入缓冲流BufferedReader
public static void main(String[] args) throws IOException {
//1 字节流对象
InputStream in = System.in;
//2 桥梁对象
InputStreamReader inr = new InputStreamReader(in);
//3 字符缓冲流
BufferedReader br = new BufferedReader(inr);
//4 接受信息
String str = br.readLine();
System.out.println(str.toUpperCase());
}
读操作:
操作一
* 读取b.txt内容:
* 1、创建字节流对象
* 2、读取
* int read();//一个字节读取
* int read(byte[] b);
* int read(byte[] b,int offset,int length);//从offset角标开始到length长度
* 3、关闭流
操作二
* 文件:File
* 文件字节输出流:FileOutputStream
* 将字符串hello world写入a.txt
* 1、创建字节流对象
* 2、void write(byte[] b)
* void write(byte[] b,int offset,int length);
* void write(int b)
* 3、关闭流
字符流
分为
字符输入流Reader()
字符输出流Writer()
字符流传化为字节流:
要把输入字符转为字节存入文本
*outputStream("c.txt");
* |OutputStreamWriter(outputStream)是 writer子类
BufferedWriter(Writer)
public static void main(String[] args) throws IOException {
FileOutputStream fi = new FileOutputStream("c.txt");
OutputStreamWriter os = new OutputStreamWriter(fi);
BufferedWriter bw = new BufferedWriter(os);
bw.write("你好");
bw.close();
}
File类
代表文件及目录路径名称
构造方法:File(File Parent,String child); (创建文件的父目录,创建文件的名称)
* File(String pathname);
* File(String parent,String child);
* File(URI uri);
* 创建:boolean createNewFile();
* 删除:boolean delete();
* void deleteOnExit(); 在jvm结束后运行
* 修改:(基本信息)
* 判断:canRead(); 判断文件是否可读
* canWrite();
* exists();
* 获取:File getAbsoluteFile(); 返回此抽象路径名形式
* String getAbsolutrPath();