緩衝位元組流和檔案操作

來源:互聯網
上載者:User

檔案操作

//用緩衝位元組流實現檔案讀寫

package DataStream;

import java.io.*;

public class BufferedStreamTest {

/**

 * @param args

 */

public static void main(String[] args) {

// TODO Auto-generated method stub

try {

FileOutputStream fos = new  FileOutputStream("res/bufferFile");

BufferedOutputStream bos = new BufferedOutputStream(fos);

DataOutputStream dos = new DataOutputStream(bos);

dos.writeUTF("hello world");

dos.writeBoolean(false);

dos.writeInt(125);

dos.flush();//清空緩衝區

fos.close();

fos.close();

dos.close();

/*需要注意的是,由於讀寫順序是從最外面開始讀取也就是說從資料輸出資料流DataOutputStream 開始讀取,其次是緩衝輸出資料流BufferedOutputStream,再其次是檔案輸出資料流FileOutStream,所以如果不寫d
os.flush 只要保證關閉的順序正確也是可以正確啟動並執行,即:

dos.close();

bos.close();

fos.close();

*/

FileInputStream fis = new              FileInputStream("res/bufferFile");

BufferedInputStream bis = new BufferedInputStream(fis);

DataInputStream dis = new DataInputStream(bis);

System.out.println(dis.readUTF()+"\n"+dis.readBoolean()+"\n"+d is.readInt());//輸出時注意與輸入時保持一致

fis.close();

bis.close();

dis.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}//新增文檔 bufferFile 直接查看會出現亂碼問題,這是正常的,由於文檔將字元型、布爾型、整型等放在一起使文檔無法識別出現亂碼,但是文檔輸出是正確的。

在寫這段代碼的時候,我們遇到了問題,由於沒有提前清空緩衝資料,導致程式運行錯誤,後來找到了錯誤的原因,原因是:

Flush()主要用在IO中,即清空緩衝區資料,就是說你用讀寫流的時候,其實資料是先被讀到了記憶體中,然後用資料寫到檔案中,當你資料讀完的時候不代表你的資料已經寫完了,因為還有一部分有可能會留在記憶體這個緩衝區中。這時候如果你調用了 Close()方法關閉了讀寫流,那麼這部分資料就會丟失,所以應該在關閉讀寫流之前先Flush(),先清空資料。

檔案操作類

檔案類(File)提供處理檔案的方法,包括:變更檔名、刪除檔案、列出目錄下的檔案以及檔案對象屬性的描述資訊等。

public   File(String  pathname);根據parent抽象路徑名和child路徑名字串建立一個新的File對象

public   File(String path,String name);根據parent路徑名字串和child路徑名字串建立一個新File對象

public   File(File  parent,String chile);通過指定路徑名字字串轉換為抽象路徑名來建立一個新的File 對象

感覺有點繞啊.......通過執行個體來解決,其實還是很簡單的

Source.txt

Backup\source.txt

執行備份:

1、判斷目錄備份是否存在,如無 建立目錄①backup②將源檔案複製到backup;如有:判斷是否需要備份,如有必要:將源檔案複製到backup,如沒必要

其他方法

  (1)訪問檔案對象

l public String getName()  //返迴文件對象名,不包含路徑名

l public String getPath()    //返回相對路徑名,包含檔案名稱

l public String getAbsolutePath()   //返回絕對路徑名,包含檔案名稱

l public String getParent()      //返回父檔案對象的路徑名

l public File   getParentFile()    //返回父檔案對象

(2)獲得檔案屬性

l public long length()     //返回指定檔案的位元組長度

l public boolean exists()    //測試指定的檔案是否存在

l public long lastModified()   //返回指定檔案最後被修改的時間

 (3)檔案操作

l public boolean renameTo(Filedest)  //檔案重新命名

l public boolean  delete()   //刪除空目錄

 (4)目錄操作

l public boolean mkdir () //建立指定日錄,正常建立時返回true

l public String[] list()    //返回目錄中的所有檔案名稱字串

l public File[] listFiles()    //返回指定目錄中的所有檔案對象

感覺有點繞啊.......通過執行個體來解決,其實還是很簡單的

例子如下:

//組建目錄檔案和輸出目錄檔案

由於操作非常簡單,按照方法就能實現,在這裡就不做示範了

//利用File自動更新檔案

package DataStream;

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.Date;

public class FileUpdateTest {

public static void main(String[] args) throws IOException{

//待覆制的檔案名稱

String fname = "source.txt";

//目標目錄名

String destdir = "backup" ;

update(fname,destdir);

}

private static void update(String fname, String destdir) throws IOException{

// TODO Auto-generated method stub

File f1,f2,dest;

//在目前的目錄中建立檔案對象 f1,dest

f1 = new File(fname);

dest = new File(destdir);

if(f1.exists()){

//dest不存在時建立目錄

if(!dest.exists()){

System.out.println("dest不存在,建立backup");

dest.mkdir();

}

//在目錄dest中建立檔案f2

f2=new File(dest,fname);

long d1 = f1.lastModified();

long d2 = f2.lastModified();

//f2 不存在時或存在但日期較早時

if((!f2.exists())||(f2.exists()&&(d1>d2))){

copy(f1,f2);//複製

}

showFileInfo(f1);

showFileInfo(dest);

}else{

System.out.println(f1.getName()+"file not found");

}

}

public static void showFileInfo(File f1) throws IOException{

// TODO Auto-generated method stub

SimpleDateFormat sdf;

sdf = new SimpleDateFormat("yyyy年MM月dd日hh時mm分");

if(f1.isFile()){

String filepath = f1.getAbsolutePath();

Date da  = new Date(f1.lastModified());

String mat = sdf.format(da);

System.out.println("<檔案:>\t"+filepath+"\t"+f1.length()+"\t"+mat);

}else{

System.out.println("<目錄:>"+"\t"+f1.getAbsolutePath());

File[]files = f1.listFiles();

for(int i = 0;i<files.length;i++){

showFileInfo(files[i]);

}

}

}

public static void copy(File f1, File f2) throws IOException {

// TODO Auto-generated method stub

//建立檔案輸入資料流對象

FileInputStream fis = new FileInputStream(f1);

//建立檔案輸入資料流對象

FileOutputStream fos = new FileOutputStream(f2);

int count,n=512;

byte buffer[] = new byte[n];

//從輸入資料流讀取資料

count = fis.read(buffer,0,n);

while(count!=-1){

//寫出輸出資料流資料

fos.write(buffer,0,count);

count = fis.read(buffer,0,n);

}

System.out.println("複製檔案"+f2.getName()+"成功!");

//關閉輸入\輸出資料流

fis.close();

fos.close();

}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.