---
title: "java文件的读写"
author: "duyunfengsolo"
date: "2009-08-21T16:09:55Z"
tags: ["Java"]
slug: "java"
draft: false
lastmod: "2009-08-21T16:49:20Z"
id: 454575
url: "https://solodu.iteye.com/blog/454575"
---

```
public File getFileFromBytes(byte[] b, String outputFile){
		BufferedOutputStream stream = null; 
        File file = null; 
        try{ 
            file = new File(outputFile); 
            FileOutputStream fstream = new FileOutputStream(file); 
            stream = new BufferedOutputStream(fstream); 
            stream.write(b); 
        } catch (Exception e){ 
            e.printStackTrace(); 
        } finally{ 
            if (stream != null){ 
                try{ 
                    stream.close(); 
                } catch (IOException e1){ 
                    e1.printStackTrace(); 
                } 
            } 
        } 
        return file; 

	}
```

 

Java代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/284993 "复制代码")

01. **public** **static** ByteArrayOutputStream readFile(String filename) {
02. **try** {
03. FileInputStream fileInStream = **new** FileInputStream(filename);
04. ByteArrayOutputStream fileByteStream = **new** ByteArrayOutputStream();
05. **int** i = 0;
06. **while** ((i = fileInStream.read()) != -1) {
07. fileByteStream.write(i);
08. }
09. fileInStream.close();
10. **return** fileByteStream;
11. } **catch** (Exception e) {
12. e.printStackTrace();
13. }
14. **return** **null**;
15. }
16. **public** **static** **void** writeFile(String fileName, **byte**\[] data) {
17. **try** {
18. FileOutputStream fos = **new** FileOutputStream(fileName);
19. fos.write(data);
20. fos.close();
21. } **catch** (Exception e) {
22. e.printStackTrace();
23. }
24. }
25. //transfor InputStream to byte
26. **public** **static** **byte**\[] getBytes(InputStream is) **throws** Exception {
27. **byte**\[] data = **null**;
28. Collection chunks = **new** ArrayList();
29. **byte**\[] buffer = **new** **byte**\[1024 * 1000];
30. **int** read = -1;
31. **int** size = 0;
32. **while** ((read = is.read(buffer)) != -1) {
33. **if** (read &gt; 0) {
34. **byte**\[] chunk = **new** **byte**\[read];
35. System.arraycopy(buffer, 0, chunk, 0, read);
36. chunks.add(chunk);
37. size += chunk.length;
38. }
39. }
40. **if** (size &gt; 0) {
41. ByteArrayOutputStream bos = **null**;
42. **try** {
43. bos = **new** ByteArrayOutputStream(size);
44. **for** (Iterator itr = chunks.iterator(); itr.hasNext();) {
45. **byte**\[] chunk = (**byte**\[]) itr.next();
46. bos.write(chunk);
47. }
48. data = bos.toByteArray();
49. } **finally** {
50. **if** (bos != **null**) {
51. bos.close();
52. }
53. }
54. }
55. **return** data;
56. }