case:实现文件复制,从指定位置复制到目标位置
* 思考,若指定文件不存在?
* 若目标位置文件已存在?
* 若目标位置目录不存在?
private static void case1() {
File btxt = new File("D:\\demo\\login.txt");
String txtName = btxt.getName();
InputStream txtFileInputStream = null;
try {
// 指定位置,获取文件内容
txtFileInputStream = new BufferedInputStream(new FileInputStream(btxt));
byte[] bytes = new byte[100];
int readCount = 0;
String result = null;
while ((readCount = txtFileInputStream.read(bytes)) != -1 ){
result = new String(bytes, 0, readCount);
System.out.println("result = " + result);
}
// 目标位置判断是否文件存在,并且粘贴内容
File ctxt = new File("D:\\demo2\\"+txtName);
// 文件不存在或目录不存在时,创建目录和文件
boolean newFile = true;
if (!ctxt.exists()) {
boolean mkdirs = ctxt.mkdirs();
boolean delete = ctxt.delete();
newFile = ctxt.createNewFile();
}
if (newFile){
FileOutputStream fileOutputStream = new FileOutputStream(ctxt);
if (result != null) {
fileOutputStream.write(result.getBytes());
}
}else {
System.out.println("文件创建失败");
}
} catch (FileNotFoundException notFoundException){
// 若指定文件不存在?
try {
btxt.createNewFile();
} catch (IOException ioException) {
ioException.printStackTrace();
}
} catch (IOException ioException) {
ioException.printStackTrace();
}finally {
try {
txtFileInputStream.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}