ITeye博客

java文件的读写

duyunfengsolo · 2009-08-21 16:09 · javaIO文件的读写 · Java · Markdown

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代码 复制代码

  1. public static ByteArrayOutputStream readFile(String filename) {
  2. try {
  3. FileInputStream fileInStream = new FileInputStream(filename);
  4. ByteArrayOutputStream fileByteStream = new ByteArrayOutputStream();
  5. int i = 0;
  6. while ((i = fileInStream.read()) != -1) {
  7. fileByteStream.write(i);
  8. }
  9. 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 > 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 > 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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。