CopyFile.java:import java.io.*;class CopyFile
{
public static void main(String args[])
{
byte b[] = new byte[1024];
int numBytes = 0;
boolean done = false; FileInputStream fin = null;
FileOutputStream fout = null;
try
{
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
}
catch(FileNotFoundException e)
{
System.out.println("Could not find" + args[0] + "!");
System.exit(0);
}
catch(Exception e)
{
System.out.println("Usage:CopyFile X Y");
System.exit(0);
}
try
{
numBytes = fin.read(b);
}
catch(IOException e)
{
System.out.println("Error!");
System.exit(0);
}
while (!done)
{
try
{
fout.write (b,0,numBytes);
}
catch(IOException e)
{
System.out.println("Error!");
System.exit(0);
}
try
{
numBytes = fin.read(b);
}
catch(IOException e)
{
System.out.println("Error!");
System.exit(0);
}
if (numBytes == -1) done = true;
}
}
}
{
public static void main(String args[])
{
byte b[] = new byte[1024];
int numBytes = 0;
boolean done = false; FileInputStream fin = null;
FileOutputStream fout = null;
try
{
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
}
catch(FileNotFoundException e)
{
System.out.println("Could not find" + args[0] + "!");
System.exit(0);
}
catch(Exception e)
{
System.out.println("Usage:CopyFile X Y");
System.exit(0);
}
try
{
numBytes = fin.read(b);
}
catch(IOException e)
{
System.out.println("Error!");
System.exit(0);
}
while (!done)
{
try
{
fout.write (b,0,numBytes);
}
catch(IOException e)
{
System.out.println("Error!");
System.exit(0);
}
try
{
numBytes = fin.read(b);
}
catch(IOException e)
{
System.out.println("Error!");
System.exit(0);
}
if (numBytes == -1) done = true;
}
}
}
然后创建一个写文件类,
然后读文件-写文件
具体可以参考API文档提供一种实现:
FileInputStream is = new FileInputStream("文件名1"); //用于读文件
FileOutputStream out = new FileOutputStream("文件名2"); //用于写文件
然后创建一个缓冲区,然后循环执行以下操作
length = is.read(buffer);
out.write(buffer, 0, length);
java CopyFile a.txt b.txt可以拷贝当前文件夹内的a.txt为b.txt,在本机测试通过!