posts - 10, comments - 4, trackbacks - 0, articles - 1

二进制文件读写

Posted on 2007-06-12 17:26 yuyu 阅读(2649) 评论(1)  编辑  收藏
package tmp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class DiskTest {
    
public static void main(String[] args) throws Exception {
        
// TODO Auto-generated method stub
        File file = new File("D:\\picture.rar");
        
byte[] content=readFile(file);
        System.out.println(content);
        writeBytes(
"D:\\picture1.rar",content);
    }


    
/**读文件到字节数组
     * 
@param file
     * 
@return
     * 
@throws Exception
     
*/

    
static byte[] readFile(File file) throws   Exception {
        
if (file.exists() && file.isFile()) {
            
long fileLength = file.length();
            
if (fileLength > 0L{
                BufferedInputStream fis 
= new BufferedInputStream(
                        
new FileInputStream(file));
                
byte[] b = new byte[(int) fileLength];
                
while (fis.read(b)!= -1{
                }

                fis.close();
                fis 
= null;

                
return b;
            }

        }
 else {
            
return null;
        }

        
return null;
    }


    
/**将字节数组写入文件
     * 
@param filePath
     * 
@param content
     * 
@return
     * 
@throws IOException
     
*/

    
static boolean writeBytes(String filePath, byte[] content)
            
throws IOException {
        File file 
= new File(filePath);
        
synchronized (file) {
            BufferedOutputStream fos 
= new BufferedOutputStream(
                    
new FileOutputStream(filePath));
            fos.write(content);
            fos.flush();
            fos.close();
        }

        
return true;

    }

}

有人在群中问如何读取写入一般文件,在这里写了一个供以后参考

Feedback

# re: 二进制文件读写  回复  更多评论   

2008-08-22 15:13 by vrin
很好 ,谢谢

只有注册用户登录后才能发表评论。


网站导航: