ITeye博客

Java文件和byte数组转换

hae · 2015-01-12 16:54 · JVM · 编程语言 · Markdown

Java代码  收藏代码

  1. public class T3 {
  2. public static void main(String[] args){
  3. String filePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src\\1.docx";
  4. String outFilePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src";
  5. String outFileName = "2.docx";
  6. getFile(getBytes(filePath),outFilePath,outFileName);
  7. }
  8. /**
  9. * 获得指定文件的byte数组
  10. */
  11. public static byte[] getBytes(String filePath){
  12. byte[] buffer = null;
  13. try {
  14. File file = new File(filePath);
  15. FileInputStream fis = new FileInputStream(file);
  16. ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
  17. byte[] b = new byte[1000];
  18. int n;
  19. while ((n = fis.read(b)) != -1) {
  20. bos.write(b, 0, n);
  21. }
  22. fis.close();
  23. bos.close();
  24. buffer = bos.toByteArray();
  25. } catch (FileNotFoundException e) {
  26. e.printStackTrace();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. return buffer;
  31. }
  32. /**
  33. * 根据byte数组,生成文件
  34. */
  35. public static void getFile(byte[] bfile, String filePath,String fileName) {
  36. BufferedOutputStream bos = null;
  37. FileOutputStream fos = null;
  38. File file = null;
  39. try {
  40. File dir = new File(filePath);
  41. if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
  42. dir.mkdirs();
  43. }
  44. file = new File(filePath+"\\"+fileName);
  45. fos = new FileOutputStream(file);
  46. bos = new BufferedOutputStream(fos);
  47. bos.write(bfile);
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. } finally {
  51. if (bos != null) {
  52. try {
  53. bos.close();
  54. } catch (IOException e1) {
  55. e1.printStackTrace();
  56. }
  57. }
  58. if (fos != null) {
  59. try {
  60. fos.close();
  61. } catch (IOException e1) {
  62. e1.printStackTrace();
  63. }
  64. }
  65. }
  66. }
  67. }

 转自:http://forai.iteye.com/blog/1221081

---------------------------------------------------------

Java IO文件操作

Java代码  收藏代码

  1. //读文件 BufferedReader
  2. BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("fileUrl"))));
  3. String tempStr = "";
  4. while((tempStr = br.readLine())!=null){
  5. System.out.println(tempStr);
  6. }
  7. //写文件 PrintWriter
  8. PrintWriter pw = new PrintWriter(new File("fileUrl"));
  9. pw.println("每一次输出一行到文件");
  10. //写文件 BufferedWriter
  11. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("fileUrl"))));
  12. bw.write("");
  13. //一次读取文件所有内容
  14. File file = new File("filePath");
  15. Long l = file.length();
  16. byte[] fc = new byte[l.intValue()];
  17. FileInputStream fis = new FileInputStream(file);
  18. fis.read(fc);
  19. fis.close();
  20. String str = new String(fc,"UTF-8");

评论(0)

暂无评论。

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