ClassNotFoundException happens during calling ObjectInputStream.readobject in Android - java

I want to read object from Android internal storage.
The following is my code.
I write a static function for reading object from file in the same class.
No idea why this exception happen .
Really appreciate if you could give some suggestions.
thanks.
package com.crescent.programmercalculator;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.util.Log;
import android.content.Context;
public class CalculateConfigurations implements Serializable{
static String configLocation="configFile";
public short radix;
CalculateConfigurations(){
radix=16;
}
public static CalculateConfigurations loadObjectFromFile(Context context){
try {
FileInputStream fis = context.openFileInput(configLocation);
ObjectInputStream is = new ObjectInputStream(fis);
CalculateConfigurations config = (CalculateConfigurations) is.readObject();
is.close();
fis.close();
return config;
} catch (FileNotFoundException e) {
// first use case
Log.v("CalculateConfigurations", "first init for configuration file");
return new CalculateConfigurations();
} catch (IOException e) {
e.printStackTrace();
Log.e("CalculateConfigurations", "Fatal error, configuration file may be broken");
return new CalculateConfigurations();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e("CalculateConfigurations", "Fatal error, unknown");
return new CalculateConfigurations();
}
}
}

ClassNotFoundException
this is in most cases some mixup in your xml-files. If you post both stacktrace and the proper xml-file, it is easy to fix it!

Read on readObject
Exceptions are thrown for problems with the InputStream and for
classes that should not be deserialized. All exceptions are fatal to
the InputStream and leave it in an indeterminate state; it is up to
the caller to ignore or recover the stream state.
Since you are trying to read an android internal library, it cannot be casted to your custom Class. Hence the ClassNotFoundException.
Hope this helps.

I encounter the same problem today. I don't know how the serialization/deserialization is done but I notice that it is very unstable process.
If you serialize some objects and put the memory, you cannot change the data type/class name easily.. If it throws class not found exception like this, remove the app from device and install again. I hope, it helps some developers :)

Related

Decoding .webm format doesn't return any BufferedImages

My code here is compiling correctly, but I am running into the problem that my ArrayList of BufferedImages is always empty. Honestly I don't have any knowledge regarding ImageIO or the likes!
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import net.sf.javavp8decoder.imageio.WebPImageReader;
import net.sf.javavp8decoder.imageio.WebPImageReaderSpi;
class MyProj{
public static void main(String[] args) throws IOException{
System.out.println("Main");
ArrayList<BufferedImage> collectedImg=getFrames();
}
static ArrayList<BufferedImage> getFrames() throws IIOException{
File MyWebM= new File("/users/case3/mcclusm4/workspace/LineTech/src/goal.webm");
ArrayList<BufferedImage> frames = new ArrayList<BufferedImage>();
try{
ImageReader ir = new WebPImageReader(new WebPImageReaderSpi());
ir.setInput(ImageIO.createImageInputStream(MyWebM));
for(int i = 0; i < ir.getNumImages(true); i++)
frames.add(ir.read(i));
}catch(IOException e){}
return frames;
}
}
First of all dont catch Exception and do nothing:
catch (Exception e) {}
Now when an exception is catched it silently fails without any information.
Change catch to print stacktrace: e.printStackTrace() and post it.
Disclaimer: I have never tested the code in question myself. But...
From looking at the source code of net.sf.javavp8decoder.imageio.WebPImageReader it cannot decode WebM files. It only supports single frame WebP files.
If you stop swallowing the exception and ignoring it, as suggested by #robocoder, you should get an IIOException with the message "Bad WEBP signature!".

Daily rollover for a FileOutputStream using Protocol Buffers?

I am getting a stream of data from a server (in binary format). This data is serialised using Google protocol buffers. I'm attempting to do a daily rollover (i.e. if next day occurs write to new file containing the new Date with the compressed data inside).
I've attempted to do this via log4j, however, log4j doesn't account for binary (as far as I know I can only get text via it). When log4j writes the files, it doesn't write them in binary, but in text (human readable) format.
I went over this question to create a custom binary appender in log4j How to Create Binary Log File in Java using Log4J
However, I only started with log4j a couple of days ago and I'm not too sure how to go about doing this.
Is there any other way to do the rollover for binary data? I'm not even sure if log4j is the best solution. I'm more than happy to try any solution you can come up with!
I want log4j to write the data in Binary not Text.
Is there any way to do a daily rollover for binary files in java?
I don't think log4j is necessary here. If you need just file rollover small stream wrapper would be enough.
Jetty project has implementation of such FileOuputStream in it's util classes RolloverFileRotator which I think fits perfectly here.
You can extend the default log4j DailyRollingFileAppender and include it in your classpath
package test.com;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.spi.LoggingEvent;
public class BinaryRollingFileAppender extends DailyRollingFileAppender {
FileOutputStream fout;
public BinaryRollingFileAppender(){
}
#Override
public void setFile(String file) {
super.setFile(file);
try {
fout = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void append(LoggingEvent le) {
try {
fout.write((byte[])le.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public boolean requiresLayout() {
return false;
}
#Override
public void close() {
try {
fout.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
then configure the appender via log4j properties file
log4j.appender.app=test.com.BinaryRollingFileAppender
log4j.appender.app.File=/tmp/binary.bin
log4j.appender.app.DatePattern='.'yyyy-MM-dd
log4j.logger.app.com=DEBUG, app
and test it
package test.com;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.log4j.Logger;
public class TestBinary {
private static final Logger LOGGER = Logger.getLogger(TestBinary.class);
public static void main(String[] args) {
Path path = Paths.get("c://tmp/binary-example-file.bin");
try {
LOGGER.debug(Files.readAllBytes(path));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I don't know if this is what you want, but is a good start point, hope this helps you.
You can use RotatingFileOutputStream with DailyRotationPolicy provided by rotating-fos Java library.

Please help me with JUnit test cases for the code below

I want to know the JUnit test cases for the following program.please help. I have not included the main method here. Want to know the JUnit test cases for the url() method in the code. This code is to read HTML from a website and save it in a file in local machine
package Java3;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Urltohtml
{
private String str;
public void url() throws IOException
{
try
{
FileOutputStream f=new FileOutputStream("D:/File1.txt");
PrintStream p=new PrintStream(f);
URL u=new URL("http://www.google.com");
BufferedReader br=new BufferedReader(new InputStreamReader(u.openStream()));
//str=br.readLine();
while((str=br.readLine())!=null)
{
System.out.println(str+"\n");
p.println(str);
}
}
catch (MalformedURLException ex)
{
Logger.getLogger(Urltohtml.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I would rename that class to UrlToHtml and write a single JUnit test class UrlToHtmlTest.
Part of the reason why you're having problems testing this is that the class is poorly designed and implemented:
You should pass in the URL you want to scrape, not hard code it.
You should return the content as a String or List, not print it to a file.
You might want to throw that exception rather than catch it. Your logging isn't exactly "handling" the exceptional situation. Let it bubble out and have clients log if they wish.
You don't need that private data member; return the contents. That lets you make this method static.
Good names matter. I don't like what you have for the class or the method.
Why are you writing this when you could use a library to do it?
Here's what the test class might look like:
public class UrlToHtmlTest {
#Test
public void testUrlToHtml() {
try {
String testUrl = "http://www.google.com" ;
String expected = "";
String actual = UrlToHtml.url(testUrl);
Assert.assertEquals(expected, actual);
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
}

Why does my test filesystem only work in memory?

I am working on a concept of a filesystem for a program. I am writing in Java (using JDK 7 u17).
To get started I built off of some tutorial that were showing my how to create a zip based filesystem using the FileSystemProvider class.
When I execute the code I have it do similar task to the examples which is copy a text file from the my desktop and place it in the zip file. The problem is once it copies the file it does not write it into the zip file, it seems to leave the file in memory which is destroyed when the program is terminated.
The problem is I cannot understand why, as far as I can tell everything looks to be in order but something is clearly not!
Oh yeah the same thing goes for directories too. If I tell the filesystem to make a new directory it just creates it in memory and there is nothing in the zip file.
Anyhow here is my working code;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class Start {
public static void main(String[] args) {
Map <String, String> env = new HashMap<>();
env.put("create", "true");
env.put("encoding", "UTF-8");
FileSystem fs = null;
try {
fs = FileSystems.newFileSystem(URI.create("jar:file:/Users/Ian/Desktop/test.zip"), env);
} catch (IOException e) {
e.printStackTrace();
}
Path externalTxtFile = Paths.get("/Users/Ian/Desktop/example.txt");
Path pathInZipFile = fs.getPath("/example.txt");
try {
Files.createDirectory(fs.getPath("/SomeDirectory"));
} catch (IOException e) {
e.printStackTrace();
}
if (Files.exists(fs.getPath("/SomeDirectory"))) {
System.out.println("Yes the directory exists in memory.");
} else {
System.out.println("What directory?");
}
// Why is the file only being copied into memory and not written out the jar/zip archive?
try {
Files.copy(externalTxtFile, pathInZipFile);
} catch (IOException e) {
e.printStackTrace();
}
// The file clearly exists just before the program ends, what is going on?
if (Files.exists(fs.getPath("/example.txt"))) {
System.out.println("Yes the file has been copied into memory.");
} else {
System.out.println("What file?");
}
}
}
I just want to add something.
Perhaps the example that you found was incomplete (I can not check since you do not references it) but in all examples I found the FileSystem instance is closed properly.
The FileSystem abstract class implements Closeable, so the close() method is called (automatically) leaving the try in the following code:
try (final FileSystem fs = FileSystems.newFileSystem(theUri, env)) {
/* ... do everything you want here ; do not need to call fs.close() ... */
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

URL connection test - compilation error

I am new to Java, have searched on the net and this forum but unable to figure out why my code is not compiling? Any help will be highly appreciated.
//filename is TestHTTPConnection.java
class TestHTTPConnection {
public static void main (String[] args){
String strUrl = "http://abc.com";
try {
URL url = new URL(strUrl);
URLConnection Conn = url.openConnection();
Conn.connect();
assertEquals(URLConnection.HTTP_OK, Conn.getResponseCode());
} catch (IOException e) {
System.err.println("Error creating HTTP connection");
e.printStackTrace();
throw e;
}
}
}
Compilation error - complains about "URL", "URLConnection" and "IOException".
You need to import those classes / interfaces !
You are missing two things:
a package line:
package yourdomain.yourapp;
and a list of imports:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
Most java developers use an IDE which automates all of this (such as NetBeans, IntelliJ IDEA, or Eclipse)
If your not using an IDE (Eclipse , NetBeans etc.) then download one which will give you content assist and point out mistakes like this.

Categories