📄 copyfile.java
字号:
//==============================================================
// CopyFile.java - Demonstrates file stream input and output
//
// Java学习源代码检索系统 Ver 1.0 20031015 免费正式版
// 版权所有: 中国IT认证实验室(www.ChinaITLab.com)
// 程序制作: ChinaITLab网校教研中心
// 主页地址: www.ChinaITLab.com 中国IT认证实验室
// 论坛地址: bbs.chinaitlab.com
// 电子邮件: Java@ChinaITLab.com
//==============================================================
import java.io.*;
public class CopyFile {
// Input a string
public static String readLine()
throws IOException {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
// Prompt for and input a string
public static String readLine(String prompt)
throws IOException {
System.out.print(prompt);
return readLine();
}
// Construct File object for named file
public static File getFileForFilename(
String filename, boolean checkExistence)
throws IOException {
File fi = new File(filename);
if (checkExistence) {
// Do not move the following statements;
// order is critical
if (!fi.exists())
throw new IOException(fi.getName() + " not found");
if (!fi.isFile())
throw new IOException(fi.getName() + " is not a file");
}
return fi;
}
// Returns true if user answers yes to prompt
public static boolean yes(String prompt)
throws IOException {
System.out.print(prompt);
char ch = (char)System.in.read();
if (ch == 'y' || ch == 'Y') {
return true;
}
return false;
}
// Copy and old file to a new one
// Overwrites or creates the new file
public static void copy(File fileOld, File fileNew)
throws IOException {
FileInputStream fin = new FileInputStream(fileOld);
FileOutputStream fout = new FileOutputStream(fileNew);
System.out.println("Copying...");
int b = fin.read();
while (b != -1) {
fout.write(b);
b = fin.read();
}
System.out.println("Finished");
}
// Main program method
public static void main(String args[]) {
String fileOldName, fileNewName;
File fileOld, fileNew;
try {
if (args.length >= 2) {
fileOldName = args[0];
fileNewName = args[1];
} else {
fileOldName = readLine("Copy what file? ");
fileNewName = readLine("To what file? ");
}
fileOld = getFileForFilename(fileOldName, true);
fileNew = getFileForFilename(fileNewName, false);
if (fileNew.isDirectory())
throw new IOException(
fileNew.getName() + " is a directory");
if (fileNew.exists()) {
if (!yes("Overwrite file " + fileNew.getName() + "? "))
throw new IOException("File not copied");
} else {
if (!yes("Create new " + fileNew.getPath() + "? "))
throw new IOException("File not copied");
}
copy(fileOld, fileNew);
} catch (IOException e) { // Trap exception
System.err.println(e.toString()); // Display error
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -