1. 程式人生 > >java IO流練習:檔案複製、遍歷子目錄、複製所有子目錄

java IO流練習:檔案複製、遍歷子目錄、複製所有子目錄

import org.junit.Test;

import java.awt.*;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;

/**
 * @author king
 *         Created by king on 2017/5/19.
 */
public class IOTrain {
    //    @Test
    public void testTime() {//測試函式執行時間
        long
start = System.currentTimeMillis(); for (int i = 0; i < 1; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); SimpleDateFormat sdf = new
SimpleDateFormat("s"); System.out.println(sdf.format(end - start)); } // @Test public void createFile() {//建立a.txt File file = new File("D:\\file\\a.txt"); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // @Test
public void fileList() {//列出D盤下的所有檔案、資料夾 File file = new File("D:"); String[] ss = file.list(); for (String s : ss) System.out.println(s); } // @Test public void fileList2() {//列出D盤下的所有檔案、資料夾 File file = new File("D:"); File[] files = file.listFiles(); for (File f : files) System.out.println(f.getPath()); } // @Test public void makeDir() {//建立資料夾 File file = new File("D:\\file\\44"); file.mkdir(); } // @Test public void testShowAllDir() {//顯示D盤下所有的子檔案 String path = "D:"; showAllDir(path); } public void showAllDir(String path) { File file = new File(path); File fs[] = file.listFiles(); for (int i = 0; i < fs.length; i++) { if (fs[i].isDirectory()) { try { showAllDir(fs[i].getAbsolutePath()); } catch (Exception e) { } } else { System.out.println(fs[i].getAbsolutePath()); } } } // @Test public void browseBaidu1() {//用瀏覽器開啟百度 try { URI uri = new URI("http://www.baidu.com"); Desktop.getDesktop().browse(uri); } catch (Exception e) { } } // @Test public void browseBaidu2() {//用瀏覽器開啟百度,完整版 String webSite = "http://www.baidu.com"; Desktop desktop = Desktop.getDesktop(); if (Desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)) { URI uri = null; try { uri = new URI(webSite); } catch (URISyntaxException e) { e.printStackTrace(); } try { desktop.browse(uri); } catch (IOException e) { e.printStackTrace(); } } } // @Test public void readByte() {// 從檔案系統中的某個檔案中獲得輸入位元組 try (FileInputStream fs = new FileInputStream("D:\\file\\1.txt")) { byte[] buffer = new byte[1024]; int n = 0; while ((n = fs.read(buffer)) != -1) { System.out.println(new String(buffer)); } } catch (IOException e) { e.printStackTrace(); } } @Test public void writeByte() {//FileOutputStream,意為檔案輸出流,是用於將資料寫入File或 FileDescriptor的輸出流。 try (FileOutputStream fs = new FileOutputStream("D:\\file\\3.txt")) { fs.write("哈爾濱".getBytes()); } catch (IOException e) { e.printStackTrace(); } } // @Test public void copyByte() {//將1.txt拷貝到2.txt try (FileOutputStream w = new FileOutputStream("D:\\file\\2.txt"); FileInputStream r = new FileInputStream("D:\\file\\1.txt")) { byte[] buffer = new byte[1024]; int n = 0; while ((n = r.read(buffer)) != -1) { w.write(buffer, 0, n); } } catch (IOException e) { e.printStackTrace(); } } // @Test public void readChar() {//FileReader類從InputStreamReader類繼承而來。該類按字元讀取流中資料。 try (Reader reader = new FileReader("D:\\file\\1.txt")) { char[] buffer = new char[20]; int n = 0; while ((n = reader.read(buffer)) != -1) { System.out.println(buffer); } } catch (IOException e) { e.printStackTrace(); } } // @Test public void writeChar() {//FileWriter類從OutputStreamReader類繼承而來。該類按字元向流中寫入資料。 try (Writer writer = new FileWriter("D:\\file\\1.txt")) { writer.write("哈爾濱"); } catch (IOException e) { e.printStackTrace(); } } // @Test public void copyChar() {//按字元流將1.txt複製給2.txt try (FileReader reader = new FileReader("D:\\file\\1.txt"); FileWriter writer = new FileWriter("D:\\file\\2.txt")) { int n = 0; char[] buffer = new char[20]; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } catch (IOException e) { e.printStackTrace(); } } // @Test public void FindFileByType() {//查詢 *.bat File file = new File("D:"); File[] find = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".bat"); } }); for (File f : find) System.out.println(f.getName()); } // @Test public void testCopyAllDir1() { String readPath = "D:\\file";//源地址 String writePath = "D:\\file2";//目標地址 new File(writePath).mkdirs(); copyAllDir1(readPath, writePath); } public void copyAllDir1(String readPath, String writePath) { File file = new File(readPath); File[] fs = file.listFiles(); for (int i = 0; i < fs.length; i++) { try { if (fs[i].isDirectory()) { fs[i].mkdir(); copyAllDir1(fs[i].getAbsolutePath(), writePath + "\\" + fs[i].getName()); } else { System.out.println(fs[i].getAbsolutePath()); } } catch (Exception e) { } } } // @Test public void testCopyAllDir2() { String readPath = "D:\\file";//源地址 String writePath = "D:\\file2";//目標地址 new File(writePath).mkdir(); copyAllDir2(readPath, writePath); } public void copyAllDir2(String readPath, String writePath) {//將readPath中的所有子檔案拷貝到writePath目錄下。 //獲取當前readPath目錄下所有檔案、資料夾,並存在fs[] 中 File file = new File(readPath); File fs[] = file.listFiles(); //fs!=null 排除空指標異常 if (fs != null) { //遍歷當前目錄 for (int i = 0; i < fs.length; i++) { //如果當前物件fs[i]是資料夾,則在目標地址中建立同名的資料夾。 if (fs[i].isDirectory()) { new File(writePath + "\\" + fs[i].getName()).mkdir(); copyAllDir2(fs[i].getPath(), writePath + "\\" + fs[i].getName()); } //如果當前物件fs[i]是檔案,那麼按位元組拷貝到目標地址。 else { try (FileInputStream readFile = new FileInputStream(fs[i].getPath());/*從這裡讀資料*/ FileOutputStream writeFile = new FileOutputStream(writePath + "\\" + fs[i].getName()))/*往這裡寫資料*/ { byte[] buffer = new byte[1024]; int n = 0; while ((n = readFile.read(buffer)) != -1) { writeFile.write(buffer, 0, n); } } catch (IOException e) { e.printStackTrace(); } } } } } // @Test public void mergeRandomAccessFile() {//將兩個mp3檔案合併。RandomAccessFile的唯一父類是Object try (RandomAccessFile r = new RandomAccessFile("c://1.mp3", "r"); RandomAccessFile w = new RandomAccessFile("c://2.mp3", "rw")) { byte[] buffer = new byte[1024 * 1024]; w.seek(1024 * 1024);//定位到末尾,MP3 avi int n = 0; while ((n = r.read(buffer)) != -1) { w.write(buffer, 0, n); } } catch (Exception e) { e.printStackTrace(); } } // @Test public void copyRandomAccessFile() {//複製檔案。RandomAccessFile已經被JDK1.4的nio的"記憶體對映檔案(memory-mapped files)"給取代了。 try (RandomAccessFile r = new RandomAccessFile("c://1.wmv", "r"); RandomAccessFile w = new RandomAccessFile("d://2.wmv", "rw")) { byte[] buffer = new byte[1024 * 1024]; int n = 0; while ((n = r.read(buffer)) != -1) { w.write(buffer, 0, n); } } catch (Exception e) { e.printStackTrace(); } } // @Test public void divideRandomAccessFile(){//將1.txt分割為多個 try(RandomAccessFile r=new RandomAccessFile("D:\\file\\1.txt","r")){ byte[] buffer=new byte[2]; int n=0; int i=1; while((n=r.read(buffer))!=-1){ RandomAccessFile w=new RandomAccessFile("D:\\file\\1_"+(i++)+".txt","rw"); w.write(buffer,0,n); } }catch (IOException e) { e.printStackTrace(); } } @Test public void mergeFile(){//將多個1_?.txt檔案合併為一個1.txt檔案 File file=null; try(RandomAccessFile w=new RandomAccessFile("D:\\file\\1.txt","rw")){ int i=1; while((file=new File("D:\\file\\1_"+(i++)+".txt")).exists()){ RandomAccessFile r=new RandomAccessFile(file,"r"); copyTo(r,w); } }catch(IOException e){e.printStackTrace();} } private void copyTo(RandomAccessFile r, RandomAccessFile w) throws IOException { byte[] buffer=new byte[8]; int n=0; while((n=r.read(buffer))!=-1){ w.write(buffer,0,n); } } }