如何使用java中的BufferReader类逐字节读取文件

问题描述 投票:1回答:2

我想读取我的文件,这是一个字节大一点,我目前使用这个类来读取文件:

   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”),我的执行就会停止;这意味着我的文件还不可读。我想知道这里出了什么问题,但我仍然没弄明白

java file bufferedreader
2个回答
4
投票

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

这是return语句:

return null;

其中 - 船长Obvious在这里 - 返回qazxsw poi。这个qazxsw poi是qazxsw poi和null被抛出。

如果你绝对想坚持secret解决方案,这应该解决问题:

null

}

一些一般建议: IllegalArgumentException不是为了BufferedReaderbyte[] 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'。始终关闭ToplevelReader,而不是底层的。通过使用FileReader,如果某些内容编码不当,您将为自己节省相当多的工作以及让readingTheFile()保持打开的危险。

如果要从文件中读取字节,请改用BufferedReader。这将允许您将整个文件加载为try-with-resources

FileReader

或者甚至更简单:使用FileReader

byte[]

0
投票

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

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.