字节流(操作字节,也可以操作字符,但是可能会产生乱码)主要有InputStream和OutputStream作为抽象基类,访问时是FileInputStream、FileOutputStream两个实现类;字符流(操作字符)主要由Reader和Writer作为抽象基类,FileReader(读取时可以一次读一行readLine())、FlieWriter作为实现类。
java中复制文件原理是就是打开一个旧文件,用输入流FileInputStream读取数据,然后在打开一个输出流FileOutputStream把数据放进去。可以理解为是两个水池,中间用byte[] 进行取水,每次取一个字节。记得放在try catch块中,关闭流的方法放在finally中。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 复制文件
* @author zxc
*
*/
public class CopyFile {
<pre name="code" class="java"><span style="white-space:pre"> </span>public static void main(String[] args){
File oldFile = new File("c:" + File.separator + "1.ini");
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
if (oldFile.exists()) {
try{
inputStream = new FileInputStream(oldFile);
outputStream = new FileOutputStream("f:" + File.separator + oldFile.getName());
byte[] buffer = new byte[1024];
int leath = 0;
while ((leath = inputStream.read(buffer)) != -1) {
outputStream.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
System.out.println("复制的文件不存在");
}
}
}
Java 7改写了所有的IO资源类,它们都实现了AutoCloseable接口,因此都可以通过自动关闭资源的try语句来关闭这些IO流
<span style="white-space:pre"> </span>public static void main(String[] args){
File oldFile = new File("c:" + File.separator + "1.ini");
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
if (oldFile.exists()) {
try(<pre name="code" class="java"><span style="white-space:pre"> </span>inputStream = new FileInputStream(oldFile);
outputStream = new FileOutputStream("f:" + File.separator + oldFile.getName());
){byte[] buffer = new byte[1024];int leath = 0;while ((leath = inputStream.read(buffer)) != -1) {outputStream.write(buffer);}} catch (IOException e) {e.printStackTrace();} }else {System.out.println("复制的文件不存在");}}