FileOutputStream
@Test
public void test4() {
//1. 创建一个File对象,表明要写入的文件位置
//输出的物理文件可以不存在,当执行过程中,不存在会自动创建
File file = new File(\"hello3.txt\");
//2. 创建一个FileOutputStream的对象,将file的对象作为形参传递给FileOutputStream的构造器中
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
//3. 写入操作
fos.write(new String(\"I love China\").getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. 关闭输出流
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
从磁盘中复制文件
//从磁盘中读取一个文件,并写入到另一个位置(相当于文件的复制)
@Test
public void test5(){
//1. 提供读入,写出的文件
File file1 = new File(\"hello1.txt\");
File file2 = new File(\"hello3.txt\");
//2. 提供相应的流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
//3. 实现文件的复制
byte[] b = new byte[5];
int len;
while ((len = fis.read(b))!= -1){
fos.write(b,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
将文件中的地址转换为参数,可以实现文件的基本拷贝的方法
File file1 = new File(\"hello1.txt\");
File file2 = new File(\"hello3.txt\");
具体每次读取大小根据文件大小决定: byte[] b = new byte[5];
继续阅读与本文标签相同的文章
上一篇 :
django中的路由系统
下一篇 :
5G于今天正式商用,但是现在换5G套餐划算么?
-
二维码如此普及,为何三维码没办法普及
2026-05-19栏目: 教程
-
山东有效专利量前十企业和前十大专院校名单来啦,第一名你想到了吗
2026-05-19栏目: 教程
-
两种ASO应用优化的核心操作方法
2026-05-19栏目: 教程
-
第126届广交会15日开幕,新产品新技术受青睐
2026-05-19栏目: 教程
-
多位知名专家建言 宁波打造中国隐形冠军之城
2026-05-19栏目: 教程
