在D盘中创建文件test.txt,文件中内容为:hello Java,然后利用流把该文件拷贝到E盘根目录中

// 在D盘中创建文件test.txt,文件中的内容为:“hello Java”
File file = new File("D:/test.txt");
StringBuilder builder = new StringBuilder();
builder.append("hello java");
OutputStreamWriter osw = null;
try {
osw = new FileWriter(file);
osw.write(builder.toString());
} catch (IOException e) {
e.printStackTrace();
} finally { // 最后一定要关闭流
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 利用流把该文件拷贝到E盘根目录下
InputStream ips = null;
OutputStream ops = null;
try {
ips = new FileInputStream(file);// 源文件
byte[] buffer = new byte[1024]; // 定义一个缓冲数组
ops = new FileOutputStream("E:/" + file.getName());// 目标文件
// 如果没有读到结尾就继续读,每次读指定的字节数
for (int len = 0; (len = ips.read(buffer)) != -1;) {
ops.write(buffer, 0, len); // 每次写出实际读取到长度
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally { // 最后关闭流
if (ips != null) {
try {
ips.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ops != null) {
try {
ops.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

简单来写:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
 
 
public class Change {
	public static void main(String[] args) throws IOException {
		FileWriter fw = new FileWriter("D:/tets.txt");
		fw.write("hello java");
		fw.close();
		FileInputStream fis = new FileInputStream("d:/tets.txt");
		FileOutputStream  fos  = new FileOutputStream("E:/tets.txt");
		byte[] b = new byte[1024];
		while(fis.read(b)!=-1)
		{
			fos.write(b);
		}
		fos.close();
		fis.close();
		
	}
}

  • 4
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值