欢迎来到天天文库
浏览记录
ID:37861088
大小:32.00 KB
页数:4页
时间:2019-06-01
《Java中File,byte[],Object间的转换》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Java中File,byte[],Object间的转换一、有两点需要注意: 1、Object对象必须是可序列化对象。 2、可序列化的Object对象都可以转换为一个磁盘文件;反过来则不一定成立,只有序列 化文件才可以转换为Object对象。二、相关的转换方法:Java代码1./* 2. * To change this template, choose Tools
2、 Templates 3. * and open the template in the editor. 4.
3、*/ 5.package javaapplication2; 6. 7.import java.io.BufferedOutputStream; 8.import java.io.ByteArrayInputStream; 9.import java.io.ByteArrayOutputStream; 10.import java.io.File; 11.import java.io.FileInputStream; 12.import java.io.FileOutputStrea
4、m; 13.import java.io.IOException; 14.import java.io.ObjectInputStream; 15.import java.io.ObjectOutputStream; 16.import java.io.Serializable; 17. 18./** 19. * 20. * @author Dao 21. */ 22.public class Main 23.{ 24. 25. public static byte[] get
5、BytesFromFile(File f) 26. { 27. if (f == null) 28. { 1. return null; 2. } 3. 4. try 5. { 6. FileInputStream stream = new FileInputStream(f); 7. ByteArrayOutputStream out = new ByteArrayOutputStream(1000); 8
6、. 9. byte[] b = new byte[1000]; 10. int n; 11. while ((n = stream.read(b)) != -1) 12. { 13. out.write(b, 0, n); 14. } 15. stream.close(); 16. out.close(); 17. 18. return out.toByteArr
7、ay(); 19. } 20. catch (IOException e) 21. { 22. e.printStackTrace(); 23. } 24. 25. return null; 26. } 27. 28. public static File getFileFromBytes(byte[] b, String outputFile) 29. { 30. BufferedOutputStream stre
8、am = null; 31. File file = null; 32. try 33. { 34. file = new File(outputFile); 35. FileOutputStream fstream = new FileOutputStream(file); 36. stream = new BufferedOutputStream(fstream); 37. stream.write(b); 38.
9、} 39. catch (Exception e) 40. { 1. e.printStackTrace(); 2. } 3. finally 4. { 5. if (stream != null) 6. { 7. try 8. { 9. stream.close(); 10. } 11. catch (IOE
此文档下载收益归作者所有