0
public class JavaApplication {
    public static void main(String[] args) throws IOException{
      URL u = new URL("https://www.javatpoint.com/java-string-valueof");
      byte[]bytes= u.openStream().readAllBytes();
      ObjectOutputStream output= new ObjectOutputStream(
              new FileOutputStream("binary.dat"));
      output.write(bytes);
      output.close();

        //Scanning the URL works just not the try and catch block
      


      try{ 
      ObjectInputStream input = new ObjectInputStream(new FileInputStream
    ("binary.dat"));
      byte[]byte1= (byte[])input.readObject();
         String any;
       for(int i=0; i<byte1.length; i++){
            any=String.valueOf(byte1[i]);
           System.out.println(any);
       }
       input.close();
     }
    catch(Exception e){
            System.out.println(e);}
    }
    
    }

I used a new byte array to read the object from file, use String.valueOf() to obtain the String value of the byte, then a for-loop to iterate the String. What am I doing wrong?

  • 1
    Try `output.writeObject` – Maurice Perry Feb 07 '23 at 08:38
  • 3
    If all you want to do is read and write `byte[]` then you don't need and should in fact avoid using `ObjectOutputStream` and `ObjectInputStream`. A plain old `InputStream`/`OutputStream` (like the `File...` variants) is more than enough for that. The `Object...` variants are for serializing Java objects in the Java-specific format using serialization. `byte[]` already have their own, very simple representation and don't need that. – Joachim Sauer Feb 07 '23 at 08:46
  • 1
    You can only read objects with `ObjectInputStream` if they were written with `ObjectOutputStream`. Based on your description, it is unlikely that is the case. – Mark Rotteveel Feb 07 '23 at 11:23
  • 1
    @MauricePerry you're right i made a silly mistake not including the writeObject. Thank you very much!! – Li's hideout Feb 07 '23 at 12:13

2 Answers2

0

As the first commenter said, your main problem was not using writeObject. The only other problem is the way you turn the bytes into text. Your code will result in the 'ascii' code of the character being printed instead of the character itself. In fact you can simplify the output code as follows:

import java.io.*;
import java.net.*;

public class JavaApplication {
    public static void main(String[] args) throws IOException {
        URL u = new URL("https://www.javatpoint.com/java-string-valueof");
        byte[] bytes = u.openStream().readAllBytes();
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("binary.dat"));
        output.writeObject(bytes);
        output.close();

        try {
            ObjectInputStream input = new ObjectInputStream(new FileInputStream("binary.dat"));
            byte[] byte1 = (byte[]) input.readObject();
            System.out.println(new String(byte1));
            input.close();
        } catch (Exception e) {
            e.printStackTrace();    
        }
    }

}
g00se
  • 3,207
  • 2
  • 5
  • 9
-1

To solve your problem, I prefer you :

  1. Add implementation of URLConnection for avoidance from Http Status 403 / Forbidden. Reference
  2. use ByteArrayOutputStream to write the byte and save it into file using ObjectOutputStream
  3. if you read with readObject() you must write with writeObject()
public class JavaApplication {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        URL u = new URL("https://www.javatpoint.com/java-string-valueof");
        URLConnection uc = u.openConnection();
        uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = null;

        try {
            is = uc.getInputStream();
            byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
            int n;
            while ((n = is.read(byteChunk)) > 0) {
                baos.write(byteChunk, 0, n);
            }
        } catch (IOException e) {
            System.err.printf("Failed while reading bytes from %s: %s", u.toExternalForm(), e.getMessage());
        } finally {
            if (is != null) {
                is.close();
            }
        }

        byte[] bytes = baos.toByteArray();
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("binary.dat"));
        output.writeObject(bytes);
        output.close();
        //Scanning the URL works just not the try and catch block

        try {
            ObjectInputStream input = new ObjectInputStream(new FileInputStream("binary.dat"));
            byte[] byte1 = (byte[]) input.readObject();
            String any;
            for (int i = 0; i < byte1.length; i++) {
                any = String.valueOf(byte1[i]);
                System.out.println(any);
            }
            input.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}
Jordy
  • 1,802
  • 2
  • 6
  • 25