简体   繁体   中英

How to read a file byte by byte using BufferReader class in java

I want to read my file which is a large one byte by byte and i currently using this class for reading the file:

   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

Now in my main class where my main method is i am trying to read the file and then try to pass it as parameter to another method of another class like below:

 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

Now in my class where calculateThresholdScheme is

   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.

But my execution stops as soon as i throw this IllegalArgumentException("null secret"); which means my file is not yet readable. I am wondering what is going wrong here but i am still not figure it out

The issue with your code lies in readingTheFile() :

This is the return-statement:

return null;

Which - Captain Obvious here - returns null . Thus secret is null and the IllegalArgumentException is thrown.

If you absolutely want to stick to the BufferedReader -solution, this should solve the problem:

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;

}

Some general advice:
BufferedReader isn't built for the purpose of reading a file byte for byte anyways. Eg '\\n' will be ignored, since you're reading line-wise. This may cause you to corrupt data while loading. Next problem: you're only closing the FileReader in readingTheFile() , but not the BufferedReader . Always close the ToplevelReader, not the underlying one. By using try-with-resources , you're saving yourself quite some work and the danger of leaving the FileReader open, if something is coded improperly.

If you want to read the bytes from a file, use FileReader instead. That'll allow you to load the entire file as 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;
}

Or alternatively and even simpler: use java.nio

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

Change your Class "File" like below, this is how it will provide you the desire mechanism. I've modified the same class you have written.

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;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM