1

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

2
  • Perhaps it's that readingTheFile() returns null no matter what? By perhaps, I mean that's definitely what it is. Commented May 24, 2016 at 13:28
  • BufferedReader is not for reading bytes, it's for reading text. Use InputStream. Commented May 24, 2016 at 18:12

2 Answers 2

4

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. E.g. '\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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

so what i should return cuz i definitely want to return the array of bytes which holds the data of the file. I do not know how to put data in this array because as i know readLine returns a string. I have done it with using Files.readAllByte which return an array of bytes but the performance is not so fast and i wanted to use buffer reader and i see at java api and i did not find any method in this buffer reader class in which i can return an array of bytes
@BarletSouth as I already pointed out, using a BufferedReader here, is a bad idea. I've edited the answer with an example showing how to do it with BufferedReader though. You can convert a String to a byte[] by using String#getBytes()
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.