基本流程
- 创建File对象
- 创建FileInputStream或FileOutputStream对象
- 读取数据或写入数据
- 关闭流
注意
- 可以处理文本文件
- 读取中文时,一个中文可能占用多个字节,使用数组作为缓冲时,可能只有中文一部分读取到了数组中,另一部分还没有读取,打印时可能会乱码,复制不会出现问题
- 使用构造器
FileOutputStream(file)
写出操作会覆盖原本的文件内容,需要使用FileOutputStream(file,true)
才会在文件末尾追加
FileInputStream fis = null;
File file = null;
try {
file = new File("hello.txt");
fis = new FileInputStream(file);
byte [] buffer = new byte[4];
int len;
while((len = fis.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.print(str);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(fis!=null){
fis.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
复制图片
File file = null;
File file1 = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
file = new File("pic1.jpg");
file1 = new File("pic2.jpg");
fis = new FileInputStream(file);
fos = new FileOutputStream(file1);
byte []bbuf = new byte[100];
int len;
while((len = fis.read(bbuf))!=-1){
fos.write(bbuf,0,len);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (fis!=null) {
System.out.println("关闭输入流");
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos!=null){
System.out.println("关闭输出流");
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
复制文件函数
public void copyFile(String srcPath,String destPath){
File src = null;
File dest = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
src = new File(srcPath);
dest = new File(destPath);
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
byte [] buffer = new byte[1024];
int len;
while((len = fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}catch (Exception e){
e.printStackTrace();
}finally {
close(fis, fos);
}
}
static void close(FileInputStream fis, FileOutputStream fos) {
try {
if (fis!=null) {
System.out.println("关闭输入流");
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos!=null){
System.out.println("关闭输出流");
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义