// 在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();
}
}