免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5479 | 回复: 2
打印 上一主题 下一主题

Java读binary file [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-08-17 04:29 |只看该作者 |倒序浏览
大家好,我有下列perl程序, $input_file是binary file:

open( IN, $input_file );
binmode IN;
undef $/;
$content = unpack("H*",<IN>);
close IN;

我要把这段写成java, 大家有什么建议?

这是我写的, 问题是速度很慢, perl用了几乎1秒钟不到,但java要将近1小时。

FileInputStream in= new FileInputStream(input);
int strLine;
while((strLine = in.read()) != -1){
    if (strLine<16){
                                    content += Integer.toHexString(0);
                                    content += Integer.toHexString(strLine);
                            }else{
                                    content += Integer.toHexString(strLine);
                            }
                    }

请大家帮忙~谢谢!

论坛徽章:
0
2 [报告]
发表于 2012-08-17 14:18 |只看该作者
呃,差别没这么大吧?
读取文件最好用一下缓冲。

而且你的操作:
{
                                    content += Integer.toHexString(0);
                                    content += Integer.toHexString(strLine);
                            }else{
                                    content += Integer.toHexString(strLine);
                            }
也是很费时间的,因为String是不可更改的对象。
优化一下就没啥问题了。

论坛徽章:
0
3 [报告]
发表于 2012-08-17 18:55 |只看该作者
不太明白,为何读取时间差距这么大。随便剽了几段程序,测试了一下Java对Binary文件的读取,感觉不是Java本身的问题。测试的程序是读取一个有1百万数据的文本文件,然后生成Binary文件,接着读取这个Binary文件,并将结果输出的另一个文件里。上述两次读,两次写,总共耗时不到3秒。测试数据文件largeT.txt在algs4-data.zip这个包里。
  1. /**
  2. * File:ReadWriteBF.java
  3. * -------------------------
  4. * Read from a large txt file ,have 1000000 data, and create a binary file;
  5. * Then Read created binary file, write a binary file again
  6. * total cost less 3 seconds
  7. */
  8. package org.cudemo;

  9. import java.io.*;

  10. import org.cudemo.In;
  11. /**
  12. * @author isaacxu
  13. *
  14. */
  15. public class ReadWriteBF {
  16.         private static String filename = "data.bf";
  17.         private static String copyfilename = "back.bf";
  18.         private static String largefilename="largeT.txt";//1000000 data
  19.         /**
  20.          * @param args
  21.          */
  22.         public static void main(String[] args) {
  23.                 //read a txt file for create a binary file
  24.                 double[] numberlist = In.readDoubles(largefilename);
  25.                 //Create a binary file
  26.                 writeToBinary(numberlist, filename);
  27.                 //read a binary file               
  28.         double[] readD = readFromBinaryFile(filename);
  29.         writeToBinary(readD, copyfilename);
  30.         
  31.        //print to console what about Binary file, cost 5 minutes
  32.         //for(double i:readD){
  33.                 //System.out.println(i);
  34.                 //}*/

  35.         }
  36.         //read a binary file
  37.          @SuppressWarnings ("unchecked")
  38.             public static <T> T readFromBinaryFile(String filename) {
  39.                 T obj = null;
  40.                 File file = new File(filename);
  41.                 if (file.exists()) {
  42.                     ObjectInputStream ois = null;
  43.                     try {
  44.                         ois = new ObjectInputStream(new FileInputStream(filename));
  45.                         obj = (T)ois.readObject();
  46.                     } catch (IOException e) {
  47.                     } catch (ClassNotFoundException e) {
  48.                     } finally {
  49.                         try {
  50.                             if (ois != null)
  51.                                 ois.close();
  52.                         } catch (IOException e) {
  53.                         }
  54.                     }
  55.                 }
  56.                 return obj;
  57.             }
  58.      //write a binary file
  59.             public static <T> void writeToBinary(T obj, String filename)
  60.             {
  61.                 try {
  62.                     FileOutputStream fis = new FileOutputStream(filename);
  63.                     ObjectOutputStream oos = new ObjectOutputStream(fis);
  64.                     oos.writeObject(obj);
  65.                 } catch (FileNotFoundException e) {
  66.                     e.printStackTrace();
  67.                 } catch (IOException e) {
  68.                     e.printStackTrace();
  69.                 }
  70.             }

  71. }
复制代码
  1. /*************************************************************************
  2. *  Compilation:  javac In.java
  3. *  Execution:    java In
  4. *
  5. *  Reads in data of various types from: stdin, file, URL.
  6. *
  7. *  % java In
  8. *
  9. *  Remarks
  10. *  -------
  11. *    - isEmpty() returns true if there is no more input or
  12. *      it is all whitespace. This might lead to surprising behavior
  13. *      when used with readChar()
  14. *
  15. *************************************************************************/
  16. package org.cudemo;

  17. import java.io.BufferedInputStream;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.net.Socket;
  22. import java.net.URL;
  23. import java.net.URLConnection;
  24. import java.util.Locale;
  25. import java.util.Scanner;


  26. /**
  27. *  <i>Input</i>. This class provides methods for reading strings
  28. *  and numbers from standard input, file input, URL, and socket.
  29. *  <p>
  30. *  The Locale used is: language = English, country = US. This is consistent
  31. *  with the formatting conventions with Java floating-point literals,
  32. *  command-line arguments (via <tt>Double.parseDouble()</tt>)
  33. *  and standard output (via <tt>System.out.print()</tt>). It ensures that
  34. *  standard input works the number formatting used in the textbook.
  35. *  <p>
  36. *  For additional documentation, see <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
  37. *  <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
  38. */
  39. public final class In {
  40.     private Scanner scanner;

  41.     // assume Unicode UTF-8 encoding
  42.     //private String charsetName = "UTF-8";

  43.     private String charsetName = "ISO-8859-1";

  44.     // assume language = English, country = US for consistency with System.out.
  45.     private Locale usLocale = new Locale("en", "US");

  46.    /**
  47.      * Create an input stream for standard input.
  48.      */
  49.     public In() {
  50.         scanner = new Scanner(new BufferedInputStream(System.in), charsetName);
  51.         scanner.useLocale(usLocale);
  52.     }

  53.    /**
  54.      * Create an input stream from a socket.
  55.      */
  56.     public In(Socket socket) {
  57.         try {
  58.             InputStream is = socket.getInputStream();
  59.             scanner = new Scanner(new BufferedInputStream(is), charsetName);
  60.             scanner.useLocale(usLocale);
  61.         }
  62.         catch (IOException ioe) {
  63.             System.err.println("Could not open " + socket);
  64.         }
  65.     }

  66.    /**
  67.      * Create an input stream from a URL.
  68.      */
  69.     public In(URL url) {
  70.         try {
  71.             URLConnection site = url.openConnection();
  72.             InputStream is     = site.getInputStream();
  73.             scanner            = new Scanner(new BufferedInputStream(is), charsetName);
  74.             scanner.useLocale(usLocale);
  75.         }
  76.         catch (IOException ioe) {
  77.             System.err.println("Could not open " + url);
  78.         }
  79.     }

  80.    /**
  81.      * Create an input stream from a file.
  82.      */
  83.     public In(File file) {

  84.         try {
  85.             scanner = new Scanner(file, charsetName);
  86.             scanner.useLocale(usLocale);
  87.         }
  88.         catch (IOException ioe) {
  89.             System.err.println("Could not open " + file);
  90.         }
  91.     }


  92.    /**
  93.      * Create an input stream from a filename or web page name.
  94.      */
  95.     public In(String s) {

  96.         try {
  97.             // first try to read file from local file system
  98.             File file = new File(s);
  99.             if (file.exists()) {
  100.                 scanner = new Scanner(file, charsetName);
  101.                 scanner.useLocale(usLocale);
  102.                 return;
  103.             }

  104.             // next try for files included in jar
  105.             URL url = getClass().getResource(s);

  106.             // or URL from web
  107.             if (url == null) { url = new URL(s); }

  108.             URLConnection site = url.openConnection();
  109.             InputStream is     = site.getInputStream();
  110.             scanner            = new Scanner(new BufferedInputStream(is), charsetName);
  111.             scanner.useLocale(usLocale);
  112.         }
  113.         catch (IOException ioe) {
  114.             System.err.println("Could not open " + s);
  115.         }
  116.     }

  117.    /**
  118.      * Does the input stream exist?
  119.      */
  120.     public boolean exists()  {
  121.         return scanner != null;
  122.     }

  123.    /**
  124.      * Is the input stream empty?
  125.      */
  126.     public boolean isEmpty() {
  127.         return !scanner.hasNext();
  128.     }

  129.    /**
  130.      * Does the input stream have a next line?
  131.      */
  132.     public boolean hasNextLine() {
  133.         return scanner.hasNextLine();
  134.     }

  135.    /**
  136.      * Read and return the next line.
  137.      */
  138.     public String readLine() {
  139.         String line;
  140.         try                 { line = scanner.nextLine(); }
  141.         catch (Exception e) { line = null;               }
  142.         return line;
  143.     }

  144.    /**
  145.      * Read and return the next character.
  146.      */
  147.     public char readChar() {
  148.         // (?s) for DOTALL mode so . matches any character, including a line termination character
  149.         // 1 says look only one character ahead
  150.         // consider precompiling the pattern
  151.         String s = scanner.findWithinHorizon("(?s).", 1);
  152.         return s.charAt(0);
  153.     }



  154.     // return rest of input as string
  155.    /**
  156.      * Read and return the remainder of the input as a string.
  157.      */
  158.     public String readAll() {
  159.         if (!scanner.hasNextLine()) { return null; }

  160.         // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
  161.         return scanner.useDelimiter("\\A").next();
  162.     }



  163.    /**
  164.      * Return the next string from the input stream.
  165.      */
  166.     public String  readString() {
  167.         return scanner.next();
  168.     }

  169.    /**
  170.      * Return the next int from the input stream.
  171.      */
  172.     public int readInt() {
  173.         return scanner.nextInt();
  174.     }

  175.    /**
  176.      * Return the next double from the input stream.
  177.      */
  178.     public double readDouble() {
  179.         return scanner.nextDouble();
  180.     }

  181.    /**
  182.      * Return the next float from the input stream.
  183.      */
  184.     public double readFloat() {
  185.         return scanner.nextFloat();
  186.     }

  187.    /**
  188.      * Return the next long from the input stream.
  189.      */
  190.     public long readLong() {
  191.         return scanner.nextLong();
  192.     }

  193.    /**
  194.      * Return the next byte from the input stream.
  195.      */
  196.     public byte readByte() {
  197.         return scanner.nextByte();
  198.     }


  199.    /**
  200.      * Return the next boolean from the input stream, allowing "true" or "1"
  201.      * for true and "false" or "0" for false.
  202.      */
  203.     public boolean readBoolean() {
  204.         String s = readString();
  205.         if (s.equalsIgnoreCase("true"))  return true;
  206.         if (s.equalsIgnoreCase("false")) return false;
  207.         if (s.equals("1"))               return true;
  208.         if (s.equals("0"))               return false;
  209.         throw new java.util.InputMismatchException();
  210.     }

  211.    /**
  212.      * Read ints from file
  213.      */
  214.     public static int[] readInts(String filename) {
  215.         In in = new In(filename);
  216.         String[] fields = in.readAll().trim().split("\\s+");
  217.         int[] vals = new int[fields.length];
  218.         for (int i = 0; i < fields.length; i++)
  219.             vals[i] = Integer.parseInt(fields[i]);
  220.         return vals;
  221.     }

  222.    /**
  223.      * Read doubles from file
  224.      */
  225.     public static double[] readDoubles(String filename) {
  226.         In in = new In(filename);
  227.         String[] fields = in.readAll().trim().split("\\s+");
  228.         double[] vals = new double[fields.length];
  229.         for (int i = 0; i < fields.length; i++)
  230.             vals[i] = Double.parseDouble(fields[i]);
  231.         return vals;
  232.     }

  233.    /**
  234.      * Read strings from a file
  235.      */
  236.     public static String[] readStrings(String filename) {
  237.         In in = new In(filename);
  238.         String[] fields = in.readAll().trim().split("\\s+");
  239.         return fields;
  240.     }

  241.    /**
  242.      * Read ints from standard input
  243.      */
  244.     public static int[] readInts() {
  245.         In in = new In();
  246.         String[] fields = in.readAll().trim().split("\\s+");
  247.         int[] vals = new int[fields.length];
  248.         for (int i = 0; i < fields.length; i++)
  249.             vals[i] = Integer.parseInt(fields[i]);
  250.         return vals;
  251.     }

  252.    /**
  253.      * Read doubles from standard input
  254.      */
  255.     public static double[] readDoubles() {
  256.         In in = new In();
  257.         String[] fields = in.readAll().trim().split("\\s+");
  258.         double[] vals = new double[fields.length];
  259.         for (int i = 0; i < fields.length; i++)
  260.             vals[i] = Double.parseDouble(fields[i]);
  261.         return vals;
  262.     }

  263.    /**
  264.      * Read strings from standard input
  265.      */
  266.     public static String[] readStrings() {
  267.         In in = new In();
  268.         String[] fields = in.readAll().trim().split("\\s+");
  269.         return fields;
  270.     }

  271.    /**
  272.      * Close the input stream.
  273.      */
  274.     public void close() { scanner.close();  }



  275.    /**
  276.      * Test client.
  277.      */
  278.     public static void main(String[] args) {
  279.         In in;
  280.         String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";

  281.         // read from a URL
  282.         System.out.println("readAll() from URL " + urlName);
  283.         System.out.println("---------------------------------------------------------------------------");
  284.         try {
  285.             in = new In(urlName);
  286.             System.out.println(in.readAll());
  287.         }
  288.         catch (Exception e) { System.out.println(e); }
  289.         System.out.println();

  290.         // read one line at a time from URL
  291.         System.out.println("readLine() from URL " + urlName);
  292.         System.out.println("---------------------------------------------------------------------------");
  293.         try {
  294.             in = new In(urlName);
  295.             while (!in.isEmpty()) {
  296.                 String s = in.readLine();
  297.                 System.out.println(s);
  298.             }
  299.         }
  300.         catch (Exception e) { System.out.println(e); }
  301.         System.out.println();

  302.         // read one string at a time from URL
  303.         System.out.println("readString() from URL " + urlName);
  304.         System.out.println("---------------------------------------------------------------------------");
  305.         try {
  306.             in = new In(urlName);
  307.             while (!in.isEmpty()) {
  308.                 String s = in.readString();
  309.                 System.out.println(s);
  310.             }
  311.         }
  312.         catch (Exception e) { System.out.println(e); }
  313.         System.out.println();


  314.         // read one line at a time from file in current directory
  315.         System.out.println("readLine() from current directory");
  316.         System.out.println("---------------------------------------------------------------------------");
  317.         try {
  318.             in = new In("./InTest.txt");
  319.             while (!in.isEmpty()) {
  320.                 String s = in.readLine();
  321.                 System.out.println(s);
  322.             }
  323.         }
  324.         catch (Exception e) { System.out.println(e); }
  325.         System.out.println();


  326.         // read one line at a time from file using relative path
  327.         System.out.println("readLine() from relative path");
  328.         System.out.println("---------------------------------------------------------------------------");
  329.         try {
  330.             in = new In("../stdlib/InTest.txt");
  331.             while (!in.isEmpty()) {
  332.                 String s = in.readLine();
  333.                 System.out.println(s);
  334.             }
  335.         }
  336.         catch (Exception e) { System.out.println(e); }
  337.         System.out.println();

  338.         // read one char at a time
  339.         System.out.println("readChar() from file");
  340.         System.out.println("---------------------------------------------------------------------------");
  341.         try {
  342.             in = new In("InTest.txt");
  343.             while (!in.isEmpty()) {
  344.                 char c = in.readChar();
  345.                 System.out.print(c);
  346.             }
  347.         }
  348.         catch (Exception e) { System.out.println(e); }
  349.         System.out.println();
  350.         System.out.println();

  351.         // read one line at a time from absolute OS X / Linux path
  352.         System.out.println("readLine() from absolute OS X / Linux path");
  353.         System.out.println("---------------------------------------------------------------------------");
  354.         in = new In("/n/fs/csweb/introcs/stdlib/InTest.txt");
  355.         try {
  356.             while (!in.isEmpty()) {
  357.                 String s = in.readLine();
  358.                 System.out.println(s);
  359.             }
  360.         }
  361.         catch (Exception e) { System.out.println(e); }
  362.         System.out.println();


  363.         // read one line at a time from absolute Windows path
  364.         System.out.println("readLine() from absolute Windows path");
  365.         System.out.println("---------------------------------------------------------------------------");
  366.         try {
  367.             in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
  368.             while (!in.isEmpty()) {
  369.                 String s = in.readLine();
  370.                 System.out.println(s);
  371.             }
  372.             System.out.println();
  373.         }
  374.         catch (Exception e) { System.out.println(e); }
  375.         System.out.println();

  376.     }

  377. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP