Java知识点之“写文件操作以及复制文件操作”

来源:互联网 发布:淘宝发货单打印软件 编辑:程序博客网 时间:2024/06/02 03:29

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

import java.io.File;

import java.io.FileOutputStream;



//写入文件操作 参数p是目标文件路径 dataStr是写入的string数据

public static void writer(String p, String dataStr) {

String path = p;
try {
FileWriter fw = new FileWriter(path, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataStr);
bw.newLine();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}


//复制文件的方法,参数src是源文件路径,dest是目标文件路径

public static void doCopyFile(String src, String dest) throws IOException {
File srcFile = new File(src);
File destFile = new File(dest);
FileInputStream input = new FileInputStream(srcFile);
try {
FileOutputStream output = new FileOutputStream(destFile);
try {
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException ioe) {
// ignore
}
}
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ioe) {
// ignore
}
}
}
原创粉丝点击