📄 chap8-5.txt
字号:
// 程序8-5
import java.io.*;
public class copyAndShow{
// 文件复制方法
void copy(String fromFile, String toFile)throws IOException{
File src=new File(fromFile); // 获得要复制的文件对象
File dst=new File(toFile);
if(!src.exists( )){
System.out.println(fromFile+" does not exist!");
System.exit(1); // 结束
}
if(!src.isFile( )){
System.out.println(fromFile+" is not a file!");
System.exit(1);
}
if(!src.canRead( )){
System.out.println(fromFile+" is unreadable!");
System.exit(1);
}
if(dst.exists( )){ // 若目标存在,确认是否可刷新
if(!dst.canWrite( )){
System.out.println(toFile+" is unwriteable!");
System.exit(1);
}
}
// 执行复制操作
FileInputStream fin=null; // 采用文件输入流
FileOutputStream fout=null;
try{
fin=new FileInputStream(src); // 创建输入流对象
fout=new FileOutputStream(dst); // 创建输出流对象
byte buffer[ ]=new byte[4096]; // 设置读取文件的缓冲区
int bytesRead; // 从缓冲区读入的字节数
// 一次读取多个字节到缓冲区,然后写入文件
while((bytesRead=fin.read(buffer))!=-1)
fout.write(buffer,0,bytesRead);
}finally{ // 无论成功与否,均要执行的部分
if(fin!=null)
try{
fin.close( ); // 关闭文件
fout.close( );
}catch(IOException e){
System.out.println("关闭文件异常");
}
}
}
// 显示文件内容方法
void showContents(String fileName)throws IOException{
File f=new File(fileName);
RandomAccessFile fin=new RandomAccessFile(f,"rw"); // 采用随机文件
System.out.println("File length: "+fin.length( )); // 文件长度
System.out.println("Pointer position:"+fin.getFilePointer( ));
// 按行显示文件内容
while(fin.getFilePointer( )<fin.length( ))
System.out.println(fin.readLine( ));
fin.close( );
}
public static void main(String args[ ]){
if(args.length!=2){
System.out.println("使用方式错误");
System.exit(1);
}
try{
// 生成一个copyAndShow类对象
copyAndShow obj=new copyAndShow ( );
obj.copy(args[0],args[1]); // 文件复制
obj.showContents(args[1]); // 显示文件内容
}catch(IOException e){
System.out.println(e.getMessage( ));
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -