Java的焦點庫java.io供給了周全的IO接口。包羅:文件讀寫、尺度設備輸出等。Java中IO是以流為根本進行輸入輸出的,所稀有據被串行化寫入輸出流,或者從輸入流讀入。
第一步調:建立一個java項目。
1、file--》new--》project...或者Model...打開建立窗口
2、輸入項目名稱“copyFile”--》finish完當作
3、項目成果如下所示:
第二步調:利用java的FileStreams復制。
特點是對于只標的目的的文件若是不存在則直接建立,若是存在直接籠蓋
完整代碼如下所示:
引入架包:
import java.io.*;
import java.nio.channels.FileChannel;
public static void testFileStreams(){
FileInputStream fls = null;//建立文件輸入
FileOutputStream fos = null;
// 建立文件輸出流
try {
fls = new FileInputStream("E:/圖片/捉妖記.jpg");
fos = new FileOutputStream("E:/file/捉妖記.jpg");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 邊輸入邊輸出(籌辦數組和temp)
byte[] bytes = new byte[1024];
//以1KB的速度
int temp = 0;
try {
//輪回輸入
while((temp=fls.read(bytes)) != -1){
try {
//寫入輸出
fos.write(bytes,0,temp);
} catch (IOException e) {
e.printStackTrace();
}
}
//刷新輸出流
fos.flush();
// 封閉輸入輸出流
fls.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
第三步調:利用Java的FileChannel復制。
FileChannel的實例現實上仍是FileStreams,不外對其進行了包裝機能上更高一下,也加倍便利一點。
代碼如下:
引入架包:
import java.io.*;
import java.nio.channels.FileChannel;
public static void testFileChannel(){
File inFile = new File("E:/圖片/捉妖記.jpg");
File outFile = new File("E:/file/捉妖記.jpg");
FileChannel inputChannel = null;
FileChannel outputChannel = null; t
ry {
inputChannel = new FileInputStream(inFile).getChannel();
outputChannel = new FileOutputStream(outFile).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}}
第四步調:利用Apache的文件東西類FileUtils。
這個利用加倍簡單,可是需要添加tomcat的架包依靠commons-io.jar。
public static void main(String[] args) {
File inFile = new File("E:/圖片/捉妖記.jpg");
File outFile = new File("E:/file/捉妖記.jpg");
try {
org.apache.commons.io.FileUtils.copyFile(inFile, outFile);
} catch (IOException e) {
e.printStackTrace();
}
}
第五步調:利用jdk供給的Files
引入架包:
import java.io.*;
import java.nio.file.Files;
這個需要jdk1.7以上版本才能撐持
public static void main(String[] args) {
File inFile = new File("E:/圖片/捉妖記.jpg");
File outFile = new File("E:/file/捉妖記.jpg");
try {
Files.copy(inFile.toPath(), outFile.toPath());
} catch (IOException e) {
e.printStackTrace();
}}
0 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!