【问题标题】:How to read a file byte by byte using BufferReader class in java如何使用Java中的BufferReader类逐字节读取文件
【发布时间】:2016-05-24 13:24:14
【问题描述】:

我想逐字节读取我的文件,我目前正在使用这个类来读取文件:

   public class File {
   public byte[] readingTheFile() throws IOException {


            FileReader in = new FileReader("/Users/user/Desktop/altiy.pdf");

                  BufferedReader br = new BufferedReader(in);

                String line;
               while ((line = br.readLine()) != null) {
                   System.out.println(line);

                }

          in.close();

      return null;

      }
 } //close class

现在在我的主要方法所在的主类中,我试图读取文件,然后尝试将其作为参数传递给另一个类的另一个方法,如下所示:

 public class myMainClass {

  // some fields here
 File f = new File ();

   public static void main (String [] a) {

    try {

            byte[] secret = five.readingTheFile();  // We call the method which read the file


           byte[][] shar = one.calculateThresholdScheme(secret, n,k);

// some other code here . Note n and k i put their values from Eclipse

      }  catch (IOException e) {

            e.printStackTrace();

                   } // close catch 

            } // close else

       } // close main

   } // close class

现在在calculateThresholdScheme所在的班级中

   public class performAlgorithm {

 // some fields here

      protected  byte[][] calculateThresholdScheme(byte[] secret, int n, int k) {

    if (secret == null)
        throw new IllegalArgumentException("null secret"); 

   // a lot of other codes below.

但是一旦我抛出这个 IllegalArgumentException("null secret"); 我的执行就会停止这意味着我的文件尚不可读。我想知道这里出了什么问题,但我仍然没有弄清楚

【问题讨论】:

  • 也许是readingTheFile()无论如何都返回null?也许,我的意思是肯定是这样的。
  • BufferedReader 不是用于读取字节,而是用于读取文本。使用InputStream

标签: java file bufferedreader


【解决方案1】:

你的代码的问题在于readingTheFile():

这是返回语句:

return null;

这 - 这里是显而易见的船长 - 返回 null。因此secretnull 并且IllegalArgumentException 被抛出。

如果你绝对想坚持BufferedReader-解决方案,这应该可以解决问题:

byte[] readingTheFile(){
    byte[] result = null;

    try(BufferedReader br = new BufferedReader(new FileReader(path))){
        StringBuilder sb = new StringBuilder();

        String line;
        while((line = br.readLine()) != null)
            sb.append(line).append(System.getProperty("line.separator"));

        result = sb.toString().getBytes();
   }catch(IOException e){
        e.printStackTrace();
   }

   return result;

}

一些一般性建议:
BufferedReader 不是为了读取文件byte 而为byte 构建的。例如。 '\n' 将被忽略,因为您正在逐行阅读。这可能会导致您在加载时损坏数据。下一个问题:您只关闭了readingTheFile() 中的FileReader,而不是BufferedReader始终关闭 ToplevelReader,而不是底层。通过使用try-with-resources,您可以为自己节省很多工作,并且如果代码不正确,您也可以避免让FileReader 处于打开状态。

如果您想从文件中读取字节,请改用FileReader。这将允许您将整个文件加载为byte[]

byte[] readingTheFile(){
    byte[] result = new byte[new File(path).length()];

    try(FileReader fr = new FileReader(path)){
        fr.read(result , result.length);
    }catch(IOException e){
        e.printStackTrace();
    }

    return result;
}

或者甚至更简单:使用java.nio

byte[] readingTheFile(){
    try{
        return Files.readAllBytes(FileSystem.getDefault().getPath(path));
    }catch(IOException e){
        e.printStackTrace();
        return null;
    }
}

【讨论】:

  • 所以我应该返回什么,因为我肯定想返回保存文件数据的字节数组。我不知道如何将数据放入这个数组,因为我知道 readLine 返回一个字符串。我已经使用 Files.readAllByte 完成了它,它返回一个字节数组,但性能不是那么快,我想使用缓冲区阅读器,我在 java api 看到,我在这个缓冲区阅读器类中没有找到任何方法,我在其中可以返回一个字节数组
  • @BarletSouth 正如我已经指出的那样,在这里使用BufferedReader 是一个坏主意。我已经用一个示例编辑了答案,该示例显示了如何使用 BufferedReader 做到这一点。您可以使用 String#getBytes()String 转换为 byte[]
【解决方案2】:

如下所示更改您的类“文件”,这就是它将如何为您提供所需的机制。我修改了你写的同一个类。

public class File {
public byte[] readingTheFile() throws IOException {

    java.io.File file = new java.io.File("/Users/user/Desktop/altiy.pdf");

    /*FileReader in = new FileReader("/Users/user/Desktop/altiy.pdf");
    BufferedReader br = new BufferedReader(in);
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    in.close();
     */
    FileInputStream fin = null;
    try {
        // create FileInputStream object
        fin = new FileInputStream(file);

        byte fileContent[] = new byte[(int) file.length()];

        // Reads bytes of data from this input stream into an array of
        // bytes.
        fin.read(fileContent);
        // returning the file content in form of byte array
        return fileContent;
    } catch (FileNotFoundException e) {
        System.out.println("File not found" + e);
    } catch (IOException ioe) {
        System.out.println("Exception while reading file " + ioe);
    } finally {
        // close the streams using close method
        try {
            if (fin != null) {
                fin.close();
            }
        } catch (IOException ioe) {
            System.out.println("Error while closing stream: " + ioe);
        }
    }
    return null;
}
}

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2012-10-18
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多