一 使用字节流读数据
read() 优化:使用死循环
FileInputStream fis = new FileInputStream("D:\\\\aaa.txt");
int a;
while((a=fis.read())!=-1){
System.out.println((char)a);
}
fis.close();
read(byte[] bytes)
FileInputStream fis = new FileInputStream("D:\\aaa.txt");
int a;
byte[] bytes = new byte[1024];
while((a=fis.read(bytes))!=-1){
//String(byte[] bytes,int offseet,int length)通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String 。
String str = new String(bytes,0,a);
System.out.println(str);
}
fis.close();
二 使用字节流写数据
read(byte[] bytes)
FileOutputStream fos = new FileOutputStream("D:\\aaa.txt");
String str = "abc";
//String类中的方法 Byte[] getBytes() 将String——>byte,存到数组中
byte[] bytes = str.getBytes();
fos.write(bytes);
fos.close();
三 文件复制
1 创建字节输入流对象,关联源文件
2 创建字节输出流对象,关联目标文件
3 循环进行读、写动作
4 释放资源
FileInputStream fis = new FileInputStream("D:\\aaa.txt");
FileOutputStream fos = new FileOutputStream("D:\\aaa(fuzhi).txt");
int a;
byte[] bytes = new byte[1024];
while((a=fis.read(bytes))!=-1){
fos.write(bytes,0,a);
}
fis.close();
fos.close();
拓展
编码:按照某种规则,将字符存储到计算机中
解码:将存储在计算机中的二进制数按照某种规则解析显示出来
ASCII GBK UTF-8
- UTF-8编码,一个中文占3个字节,数字、字母、标点占1个字节
- GBK编码,一个中文占2个字节,数字、字母、标点占1个字节
- 换行 fos.write( "\r\n".getBytes());
1 编码
byte[] getBytes() 将String——>byte,结果存到数组中
byte[] getBytes(String charsetName) 使用指定字符集
2 解码
String(byte[] bytes) 将byte——>String
String(byte[] bytes,String charsetName)
验证字符集
Charset.defaultCharset()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY