java常用的文件讀寫操作

jopen 10年前發布 | 90K 次閱讀 Java開發 Java

現在算算已經做java開發兩年了,回過頭想想還真是挺不容易的,java的東西是比較復雜但是如果基礎功扎實的話能力的提升就很快,這次特別整理了點有關文件操作的常用代碼和大家分享

1.文件的讀取(普通方式)

(1)第一種方法

    File f=new File("d:"+File.separator+"test.txt");  
    InputStream in=new FileInputStream(f);  
    byte[] b=new byte[(int)f.length()];  
    int len=0;  
    int temp=0;  
    while((temp=in.read())!=-1){  
           b[len]=(byte)temp;  
           len++;  
    }  
    System.out.println(new String(b,0,len,"GBK"));  
    in.close();  
</div> </div>
這種方法貌似用的比較多一點

(2)第二種方法

    File f=new File("d:"+File.separator+"test.txt");  
    InputStream in=new FileInputStream(f);  
    byte[] b=new byte[1024];  
    int len=0;  
    while((len=in.read(b))!=-1){  
        System.out.println(new String(b,0,len,"GBK"));  
     }  
    in.close();  
</div> </div>
2.文件讀取(內存映射方式)
    File f=new File("d:"+File.separator+"test.txt");  
    FileInputStream in=new FileInputStream(f);  
    FileChannel chan=in.getChannel();  
    MappedByteBuffer buf=chan.map(FileChannel.MapMode.READ_ONLY, 0, f.length());  
    byte[] b=new byte[(int)f.length()];  
    int len=0;  
    while(buf.hasRemaining()){  
       b[len]=buf.get();  
        len++;  
     }  
    chan.close();  
    in.close();  
    System.out.println(new String(b,0,len,"GBK"));  
</div> </div>

這種方式的效率是最好的,速度也是最快的,因為程序直接操作的是內存

 

3.文件復制(邊讀邊寫)操作

(1)比較常用的方式

 
package org.lxh;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class ReadAndWrite {

public static void main(String[] args) throws Exception {  
    File f=new File("d:"+File.separator+"test.txt");  
    InputStream in=new FileInputStream(f);  
    OutputStream out=new FileOutputStream("e:"+File.separator+"test.txt");  
    int temp=0;  
    while((temp=in.read())!=-1){  
        out.write(temp);  
    }  
    out.close();  
    in.close();  
}  

} </pre></div>
(2)使用內存映射的實現

package org.lxh;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadAndWrite2 {

public static void main(String[] args) throws Exception {
File f=new File("d:"+File.separator+"test.txt");
FileInputStream in=new FileInputStream(f);
FileOutputStream out=new FileOutputStream("e:"+File.separator+"test.txt");
FileChannel fin=in.getChannel();
FileChannel fout=out.getChannel();
//開辟緩沖
ByteBuffer buf=ByteBuffer.allocate(1024);
while((fin.read(buf))!=-1){
//重設緩沖區
buf.flip();
//輸出緩沖區
fout.write(buf);
//清空緩沖區
buf.clear();
}
fin.close();
fout.close();
in.close();
out.close();
}

} </pre></div> </div> </div> 來自:http://blog.csdn.net/smartcodekm/article/details/25914785

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!