歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java 實現大文件的分割與合並

Java 實現大文件的分割與合並

日期:2017/3/1 11:09:36   编辑:Linux編程
  1. package namespace;
  2. import java.io.*;
  3. public class Study
  4. {
  5. private static int length=1024;//可以設置文件在讀取時一次讀取文件的大小 
  6. /*
  7. * 文件的切割
  8. * String path 切割文件的路徑
  9. * size      子文件的大小
  10. * */
  11. public static void filesplit(String path,int size)throws Exception
  12. {
  13. if(path==null)
  14. throw new Exception("源文件不能為空...");
  15. File file=new File(path);
  16. if(!file.exists())
  17. throw new Exception("源文件不存在...");
  18. long num=file.length()%size==0?file.length()/size:file.length()/size+1;
  19. String list[]=new String[(int)num];//用於存放分割後的結果
  20. FileInputStream reader=new FileInputStream(file);
  21. long beginIndex=0,endIndex=0;
  22. int readcount=0;byte buffer[]=new byte[length];
  23. for(int i=0;i<num;i++)
  24. {
  25. list[i]=file.getAbsolutePath()+".depart"+i+".rmvb";
  26. FileOutputStream writer=new FileOutputStream(list[i]);
  27. endIndex=(endIndex+size)>file.length()?file.length():endIndex+size;
  28. for(;beginIndex<endIndex;)
  29. {
  30. if(endIndex-beginIndex>=length) {
  31. readcount=reader.read(buffer);
  32. beginIndex+=readcount;
  33. writer.write(buffer);
  34. }else {
  35. //下面的就不能直接讀取1024個字節了,就要一個一個字節的讀取了
  36. for(;beginIndex<endIndex;beginIndex++)
  37. {
  38. writer.write(reader.read());
  39. }
  40. continue;
  41. }
  42. }
  43. writer.close();
  44. }
  45. }
  46. public static void union(String path,String newString)throws Exception
  47. {
  48. File file=new File(path);
  49. File list[]=file.listFiles();
  50. File newFile=new File(newString);
  51. byte buffer[]=new byte[1024];
  52. int readcount;
  53. if(!newFile.getParentFile().exists())
  54. throw new Exception("你合並的文件夾的不存在...");
  55. FileOutputStream writer=new FileOutputStream(newString);
  56. for(File f:list)
  57. {
  58. FileInputStream reader=new FileInputStream(f);
  59. while((readcount=reader.read(buffer))!=-1)
  60. {
  61. writer.write(buffer);
  62. }
  63. reader.close();
  64. }
  65. writer.close();
  66. }
  67. public static void main(String args[])throws Exception
  68. {
  69. // filesplit("F:\\movie\\movie.rmvb",104857600);
  70. //union("F:\\movie\\","F:\\movie.rmvb");
  71. }
  72. }
  73. /*
  74. * 文件的分割與合並
  75. * 1.文件的分割,原理是用輸入流去讀取文件,將讀取規定大小的流再輸出支指定的文件,直到整個把整個文件讀取結束.
  76. * 2.文件合並,文件的合並原理與分割正好想反,就是把所有的文件都讀取到一個輸入流中,然後再把輸入流中的東西全部輸出到
  77. *   同一個文件輸出流中,這樣就可以把分割的文件合並到一個文件中去了. 並且文件的大小和原來也會一樣 . 
  78. * 3.上面的程序我試著分割一個600多M 的電影,分割是成功了,但只是分割的第一個文件可以播放,而後面的幾個文件都不可以播放,我也不知道為什麼,
  79. * 可能是視頻文件裡面有什麼自定的格式吧...不過分割後再把所有的文件合並,合並後文件大小和之前一樣,而且還可以插入,說明文件沒有分割壞
  80. * 至於單個的文件為什麼不能插入,這個以後用到的時候再去研究..現在還是把Java的基礎搞懂再說..... 
  81. * 2011.10.21 9:43
  82. * * *
  83. *
  84. *
  85. * */
Copyright © Linux教程網 All Rights Reserved