Reading object from file using ObjectInputStream? ClassNotFoundException - java

In previous code in my program, I had saved an ArrayList (consisting of objects of a custom class called location as you can see in my code) in a file using ObjectOutputStream and FileOutPutStream. However, when trying to retrieve the object from the file, using ObjectInputStream, I am getting an error saying that I have an unhandled exception (ClassNotFoundException).
Here's the code I used to get the ArrayList out of the file:
String file = "file";
ObjectInputStream input = new ObjectInputStream(new FileInputStream("file"));
ArrayList<location> arrayList = new ArrayList<location>();
arrayList = (ArrayList) input.readObject();
The error is on the line where I call the .readObject() method. Any Help will be appreciated as I am new to Java. Thank You!

That means the class you sent could not be found in your app. You have to add it to the class path of the app, or only send classes the app has. In your case, the missing class will be in the ArrayList as ArrayList will always be there.
Nothing mysterious is going on, the error means just what it says.
It would be more useful if the exception told you which class was missing. I think Java 7 does this now.

Related

Java NoSuchFileException When File Exists

I am attempting to parse a json file as part of an android development project. Here is the error message that keeps popping up:
W/System.err: java.nio.file.NoSuchFileException: C:/Users/andno/Desktop/AndroidDev2ClimateApp/app/src/main/java/com/example/androiddev2climateapp/ui/home/test.json
However, in android studios, the path in the error is supplied as a link, which I can click, leading me to the write file- thus, I don't think the path is wrong.
Here is my code:
String first = "C:/Users/andno/Desktop/AndroidDev2ClimateApp/app/src/main/java/com/example/androiddev2climateapp/ui/home/test.json";
try {
String fileContents = new String((Files.readAllBytes(Paths.get(first))));
JSONObject json = new JSONObject(fileContents);
JSONArray widgets = new JSONArray("WidgetArray");
for(int i = 0; i < widgets.length(); i++){
int id = widgets.getJSONObject(i).getInt("id");
System.out.println(id);
}
} catch(IOException | JSONException e){
e.printStackTrace();
}
Sorry that the formatting is messed up. I have tried using \ in the path instead of / as well, but it doesn't work. Any help would be greatly appreciated- thanks so much!
You may be able to get this code to work when you're testing, but obviously, there is no C:\Users\andno on your android phone and there never will be.
You're barking up the wrong tree. You don't want to read a file at all.
You want to read a resource from the same place java (or, rather, android) is loading the class file (or whatever passes for class file in android). Which is probably from within a jar or apk or whatnot.
UiMain.class.getResource("test.json")
or
UiMain.class.getResourceAsStream("test.json")
will get you a resource named test.json from the same place that UiMain.class is located (i.e. in the same package, I'm assuming this is class com.example.android.androiddev2climateapp.home.ui.UiMain. The first one as a URL, which you can usually pass to constructors of images and the like, and the second as stream, which you'd need to safely close (try/finally or try-with-resources if android has gotten around to adding that 20 year old java feature already), and which you can turn into a string using various APIs. Probably the JSON API itself can just be fed an inputstream.

Save class to file from URLClassLoader? and decompile it?

It's possible to save class from URLClassLoader to normal file.class? and then decompile it?
I trying save it just as object using
Class<?> clazz = classLoader.loadClass("foo.Bar");
FileOutputStream sf = new FileOutputStream(f);
ObjectOutputStream s = new ObjectOutputStream(sf);
s.writeObject(clazz);
s.close();
Bu that don't work.
So... how to decompile it? I need get something like result of jd-gui, but using class from URLClassLoader.
You need to map the class name (e.g. "foo.Bar") to a resource path name (e.g. "/foo/Bar.class") and then use classLoader.getResourceAsStream to open a stream to read the bytecode file.
In theory, this can then be fed to a decompiler ... assuming that you have a decompiler that can read from an InputStream.
What you are doing at the moment fails because a Class object cannot be serialized.
Do a simple HTTP download, rather than URLClassLoader, to get the class into a file. Then decompile that.
(Writing an object to an ObjectOutputStream only saves the data in an instance of the object, and even that works only if the object has implemented Serializable. Not what you're looking for here.)

ObjectInputStream Handling classNotFoundException

I have an issue while reading the data from a file using objectInputStream. Please find the code below
File file = new File("model.pst")
if (file.exists()) {
fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
input = (List<GlobalModel>) in.readObject();
in.close();
}
I got to know from the ObjectOutputStream http://docs.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html docs, that while writing the object to the file, he default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.I have an issue where the class name has been changed after writing the object to the file and when I use the above code to read the values, its throwing a classNotFound exception. I would like to know if there is a way, I can handle this exception, i.e once it comes to the exception block, can I replace the classname in the object that is being read to the new class name and make it work ?
Please Assist. Thanks in Advance
I've never done this myself but it should be possible to replace a class by another by making a subclass of object input stream and overriding the resolveClass method, http://docs.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html#resolveClass(java.io.ObjectStreamClass)

Writing Data to Internal File - ContextWrapper NullPointerException

I'm creating a file for internal storage, and I'm running into a problem when the data is written. I know that it retrieves the right data when it's called (I used a Logcat tag to check that it was), but as soon as it tries to open the FileOutputStream, it says that there is a NullPointerException on the second line:
static ContextWrapper wrap = new ContextWrapper(context);
FileOutputStream gamesave = wrap.openFileOutput (FILENAME, Context.MODE_PRIVATE);
gamesave.write(DATA.getBytes());
gamesave.close();
I've looked at other questions and I can't figure out why the NullPointerException is there, it seems to be following the right procedure.
I think you have the wrong Context in your context var (i.e. ApplicationContext). Try using the context directly - without the Wrapper.
Why are you creating a ContextWrapper? There is no reason to do that. Just use the Context you have at hand -- the Activity if you are an Activity, or one passed in to your code if not.
Note that it is perfectly fine to use the Application as a Context for this.

How best to make "accessable" File I/O Stream constructors (channel & ByteBuffer also)

I'd like to know how best to make "accessable" or "visible" a set of File I/O Stream constructors defined in my main routine, to sub-routines.
I found that I cannot use "public", the compiler issues an "Illegal Expression" error msg.
When I place the file I/O stream and channel constructors in the public class defined for
the entire program "package". The compiler issues an error stating there's no FileNotFound or IOException handling declared, so I put on my mainline routine the following:
public static void main(String args[]) throws FileNotFoundException, IOException
{
// and if I then place the File I/O contructors after this:
//Connect to the LU62XC Message File
FileOutputStream MesgOut = new FileOutputStream(Mesg_File) ;
FileChannel MesgChnl = MesgOut.getChannel() ;
ByteBuffer Mesg_Bufr = ByteBuffer.allocate(128) ;
//Connect to the Request Input File
FileInputStream RqstInp = new FileInputStream(Rqst_File) ;
//Connect to the Response Output File
FileOutputStream RespOut = new FileOutputStream(Resp_File) ;
//Connect to the Request/Response Log File
FileOutputStream LogrOut = new FileOutputStream(Logr_File) ;
I resolve the "no exception handling error", but now my problem is the sub-routines
that reference the "constructed" file objects essentianlly can't .. I get a bunch of
"symbol not found" error messages. Again, if I put "public" in front of the file I/O constructors, I get the Illegal expression message.
Is there any way out of this ???
Why the java compiler insists on the program handling file-not-found errors is beyond me.
I mean there's already the if file_object.exists() method...
IF the file's NOT there.. the OS will let you know. All ANY application program(OOP or otherwise) does when it comes to I/O of any kind is to make a request to the underlying OS.
If you want a method to use an object you have as a local variable you can pass its as an argument. This is standard practice in just about every language I can think of. However instead of passing the FileInputStream it is better to pass the file name in camelCase
// in main
process(requestFile, responseFile, logFile);
// later
public static void process(String requestFile, String responseFile, String logFile) throw IOException {
//Connect to the Request Input File
FileInputStream requestIn = new FileInputStream(requestFile);
//Connect to the Response Output File
FileOutputStream responseOut = new FileOutputStream(responseFile);
//Connect to the Request/Response Log File
FileOutputStream logOut = new FileOutputStream(logFile);
requestIn.close();
responseOut.close();
logOut.close();
}
I get a bunch of "symbol not found" error messages.
Because a local variable is local to the scope i.e. the method it is in. You can't use it in another method.
Again, if I put "public" in front of the file I/O constructors, I get the Illegal expression message.
Because public fields cannot be defined in a method, they have to be define outside a method, usually at the start of the class.
Is there any way out of this ???
Reading a few tutorials http://www.google.com/search?q=java+turorials 11 million results, or working example http://www.google.com/search?q=java+examples 25 million results
Why the java compiler insists on the program handling file-not-found errors is beyond me. I mean there's already the If file_object.exists() method... IF the file's NOT there..the OS will let you know.
It does let you know by throwing a FileNotFoundException. What do you expect it to do?
All ANY application program(OOP or otherwise) does when it comes to I/O of any kind is to make a request to the underlying OS.
And the OS can return an error which you need to be able to handle.
This is basic Java: you have to pass references the methods that need them, or create them as instance variables and instantiate a class.
I suggest you read the "Getting Started" tutorial: http://download.oracle.com/javase/tutorial/java/index.html

Categories

Resources