智能网站建设加工,高端网站建设慕枫,网站空间购买费用,查看wordpress版本文章目录 字节 流FileOutputStream换行 与 续写FileInputstream实现 文件拷贝#xff08;字节数组 读入方法#xff09;字节流 编码 字节 流
FileOutputStream
创建对象#xff0c;指定位置#xff08;产生数据传输通道#xff09; 参数可以是File对象#xff0c;也可以… 文章目录 字节 流FileOutputStream换行 与 续写FileInputstream实现 文件拷贝字节数组 读入方法字节流 编码 字节 流
FileOutputStream
创建对象指定位置产生数据传输通道 参数可以是File对象也可以是路径 如果文件不存在且父级路径正确会新建文件 如果文件存在会清空文件写出数据 ASCII对应 字符 可以传入字节流指定起始位置长度释放资源 解除资源占用
package com.io.testdemo1;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class test1 {public static void main(String[] args) throws IOException {// 创建对象指定位置产生数据传输通道FileOutputStream fos new FileOutputStream(src/aaa.txt);// 写入数据fos.write(97);byte[] bytes {97, 98, 99, 100};fos.write(bytes);fos.write(bytes, 0, 2);// 释放资源fos.close();}
}换行 与 续写
换行 write(“\r\n”) 即可 linux只写\n即可 mac写\r \r 表示回车 \n 表示换行 早期\r表示回到此行开头\n才表示换行一直沿用了下来。
续写 在输出流对象的第二个参数中加入true表示打开续写开关。
例子
package com.io.testdemo1;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class test1 {public static void main(String[] args) throws IOException {FileOutputStream fos new FileOutputStream(src/aaa.txt, true);// 写入数据String str1 hello;byte[] bytes1 str1.getBytes();fos.write(bytes1);// 写入换行String str2 \r\n;byte[] bytes2 str2.getBytes();fos.write(bytes2);fos.close();}
}运行两次的结果
可以发现第二次续写了并没有清空同时换行了。
FileInputstream
与输出相似。
创建对象搭建桥梁 如果文件不存在则直接报错读入返回值为int 一次读一个字节ASCII对应的数字 (每次读相当于一次指针的移动) 读到末尾时返回-1释放资源
package com.io.testdemo2;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;public class test2 {public static void main(String[] args) throws IOException {// 创建对象FileInputStream fis new FileInputStream(src/aaa.txt);// 循环 读入int b; // 用变量去接收要是条件和循环体内都read会跳两次while ((b fis.read()) ! -1) {System.out.print((char)b);}// 释放资源fis.close();}
}运行结果与文件内容相同说明成功读取成功
实现 文件拷贝字节数组 读入方法
read可以传入byte数组这样可以一次读入一个字节数组大小速度会快很多大小最好为1024的整数倍。
注意返回值变成了长度读完会返回-1。
将aaa.txt拷贝bbb.txt
package com.io.copydemo;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class test3 {public static void main(String[] args) throws IOException {FileInputStream fis new FileInputStream(src/aaa.txt);FileOutputStream fos new FileOutputStream(src/bbb.txt);byte[] bytes new byte[4096];int len;while ((len fis.read(bytes)) ! -1) {fos.write(bytes, 0, len);}fis.close();fos.close();}
}运行结果
字节流 编码
最好不要用字节流取读取文本文件。 编码和解码要统一。
idea默认utf-8字母1字节汉字3字节 eclipse默认jbk字母1字节汉字2字节
package com.io;import java.io.UnsupportedEncodingException;public class demo4 {public static void main(String[] args) throws UnsupportedEncodingException {String str abc你好;byte[] bytes str.getBytes(GBK);String res1 new String(bytes, GBK);String res2 new String(bytes, UTF-8);System.out.println(res1); // abc你好System.out.println(res2); // abc}
}