How to serialize and deserialize in android? - java

my mainActivity has a ListView which should display my CustomList:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class CustomList implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<Game> list = new ArrayList<Game>();
public void add(Game toAdd){
list.add(toAdd);
}
public Game get(int id){
return list.get(id);
}
public ArrayList<Game> getList(){
return list;
}
public void serialize(){
try {
FileOutputStream fo = new FileOutputStream("res\\data.dat");
ObjectOutputStream ou = new ObjectOutputStream(fo);
ou.writeObject(list);
ou.close();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void deserialize(){
try {
FileInputStream fi = new FileInputStream("res\\data.dat");
ObjectInputStream oi = new ObjectInputStream(fi);
list = (ArrayList<Game>)oi.readObject();
oi.close();
fi.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I get the following error trying to serialize or desirialize:
java.io.FileNotFoundException: res\data.dat: open failed: ENOENT (No such file or directory)
My question is how to proper point to my data.dat file.
Thanks in advance

You can't write into the res directory (that's read-only), you have to write to somewhere else, e.g. to the cache directory (if it's only temporary; use context.getCacheDir() to get it's location) or to some permanent space (e.g. context.getFilesDir()).
You can get the file location like this, what you can pass to the FileOutputStream's or the FileInputStream's constructor:
File file = new File(context.getFilesDir(), "data.dat");
You may also have to request permission to write to external storage if you choose so.
Read more about storing files in Android here: http://developer.android.com/training/basics/data-storage/files.html

Related

java.io.FileNotFoundException: class path resource even though file exists in src/main/resources

I have my XML file under the src/main/resources directory. My spring code looks like
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.springframework.core.io.ClassPathResource;
import org.springframework.integration.xml.transformer.XsltPayloadTransformer;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class BdeApplicationController {
#GetMapping("/ping")
#ResponseBody
public String ping(#RequestParam(name="name", required=false, defaultValue="Stranger") String name) {
return myFlow();
}
private String myFlow() {
XsltPayloadTransformer transformer = getXsltTransformer();
return transformer.transform(buildMessage(getXMLFileString())).toString();
}
private String getXMLFileString() {
try {
return Files.toString(new ClassPathResource("XML1.xml").getFile(), Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private XsltPayloadTransformer getXsltTransformer() {
return new XsltPayloadTransformer(new ClassPathResource("XSLT1.xsl"));
}
protected Message<?> buildMessage(Object payload) {
return MessageBuilder.withPayload(payload).build();
}
}
On running this code I get the following exception: -
java.io.FileNotFoundException: class path resource [XML1.xml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/user/Documents/project/target/bde-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/XML1.xml
Can you please suggest how can I fix this?
When you use resource.getFile() you look for the file in the file system, thats why it does't work when you runnit as a jar.
Try with a InputStream
String data = "";
ClassPathResource resource = new ClassPathResource("/XML1.xml");
try {
byte[] dataArr = FileCopyUtils.copyToByteArray(resource.getInputStream());
data = new String(dataArr, StandardCharsets.UTF_8);
} catch (IOException e) {
// do whatever
}
You have no File inside jar archive: use InputStream
Once you have the resource (via ClassPathResource) you should use getInputStream() to get its contents independently of where it is located. This way will work inside your IDE (actually a File there) and also when running the jar on the server (inside the jar archive, not exactly a File).
You need only modify your getXMLFileString() method so it uses the InputStream instead of the File:
private String getXMLFileString() {
String xml;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
xml = reader.lines().collect(Collectors.joining("\n"));
reader.close();
} catch (IOException e) {
e.printStackTrace();
xml = null;
}
return new String(xml, Charsets.UTF_8);
}

Write and read object to and from file

I want to read and write an object to a file. This is my attempt:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class SaveOpen implements Serializable
{
private static String fileName;
private ArrayList<Person> list = new ArrayList<Person>();
public SaveOpen() {
fileName = "file.txt";
}
//Reader
public static Object deserialize() throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
Object obj = ois.readObject();
ois.close();
return obj;
}
//Writer
public static void serialize(Object obj)
throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public ArrayList<Person> getListPersons() {
return list;
}
}
However, I do not know if this is the correct way nor how to implement this in a class. The object is Person and I want to save and read that object from a file. Is it supposed to be done to a .txt file? Anyone who can clearify things? Thanks!
if you want the file to be human readable i would suggest to save it as xml.
Example :
Object Class
import java.io.Serializable;
public class Person implements Serializable
{
private String username;
private int id;
public String UserName() { return username; }
public void setUserName(String str) { username = str;}
public int ID() { return id; }
public void setID(int ID) { id = ID; }
}
-Serializer/Deserializer
import Settings.Person;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class XmlSerializer
{
//File path to serialize to and deserialize from
private static final String SERIALIZED_FILE_NAME = "yourSavePath.xml";
//Insert person object and save as xml file to chosen filepath
public static void Serialize(Person person)
{
try
{
FileOutputStream os = new FileOutputStream(SERIALIZED_FILE_NAME);
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(person);
encoder.close();
}
catch(FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
//Deserialize xml file into person object
public static Person Deserialize()
{
try
{
FileInputStream os = new FileInputStream(SERIALIZED_FILE_NAME);
XMLDecoder decoder = new XMLDecoder(os);
Person p = (Person)decoder.readObject();
decoder.close();
return p;
}
catch(FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
return null;
}
}
You're doing it right already. You can safe Objects in a txt file altough it makes not much sense, I'd rather go with a binary file.
To store multiple Objects in a single File, simply pack them in a Collection and then serialize the Collection object.
When reading an Object from a File, check its Class via instanceof and cast it to whatever it is.

Making changes in the properties file of Java project

I need to make a change in .properties file in my Java project. This is later deployed as a jar and used by other Java project. But according to this, I see that we should not directly make the change instead create a new object. Where should we create that new object and how can we make sure that its changes are visible?
Yes that's correct if your properties files is inside a jar then you won't be able to directly change that properties file since its packaged and zipped up in an archive. Instead you can create/change the file placed on a drive and read it, I used "user.home" for an example which you can change it as your need, below is the code for the same:
package com.test.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropertyFileReader {
private static final Logger LOGGER = LoggerFactory
.getLogger(PropertyFileReader.class);
private static Properties properties;
private static final String APPLICATION_PROPERTIES = "application.properties";
private static final String workingDir = System.getProperty("user.home");
private static File file = new File(workingDir, APPLICATION_PROPERTIES);
static {
properties = new Properties();
}
public static void main(String[] args) {
write("hello", "2");
System.out.println(read("hello"));
}
public static String read(final String propertyName) {
try (InputStream input = new FileInputStream(file)) {
properties.load(input);
} catch (IOException ex) {
LOGGER.error("Error occurred while reading property from file : ",
ex);
}
return properties.getProperty(propertyName);
}
public static void write(final String propertName,
final String propertyValue) {
try (OutputStream output = new FileOutputStream(file)) {
properties.setProperty(propertName, propertyValue);
properties.store(output, null);
} catch (IOException io) {
LOGGER.error("Error occurred while writing property to file : ", io);
}
}
}

How to render PNG image from DFX file by using kabeja package?

I'm new to this kabeja package so please can some one provide code example or reading material to render PNG from DXF file using Java?
This is the sample code that generate PNG image from DXF file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.parser.*;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.SVGGenerator;
import org.kabeja.xml.*;
public class MyClass {
public static void main(String[] args) {
MyClas x=new MyClas();
x.parseFile("C:\\Users\\Space\\Desktop\\test2.dxf");
}
public void parseFile(String sourceFile) {
try {
FileOutputStream o=new FileOutputStream("C:\\Users\\Space\\Desktop\\test2.png");
InputStream in = new FileInputStream(sourceFile);//your stream from upload or somewhere
Parser dxfParser = ParserBuilder.createDefaultParser();
dxfParser.parse(in, "");
DXFDocument doc = dxfParser.getDocument();
SVGGenerator generator = new SVGGenerator();
//org.xml.sax.InputSource out = SAXPNGSerializer;
SAXSerializer out = new org.kabeja.batik.tools.SAXPNGSerializer();
out.setOutput(o);
generator.generate(doc,out,new HashMap());
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
Hope you get what you required :)

How to read MP3 file tags

I want to have a program that reads metadata from an MP3 file. My program should also able to edit these metadata. What can I do?
I got to search out for some open source code. But they have code; but not simplified idea for my job they are going to do.
When I read further I found the metadata is stored in the MP3 file itself. But I am yet not able to make a full idea of my baby program.
Any help will be appreciated; with a program or very idea (like an algorithm). :)
The last 128 bytes of a mp3 file contains meta data about the mp3 file., You can write a program to read the last 128 bytes...
UPDATE:
ID3v1 Implementation
The Information is stored in the last 128 bytes of an MP3. The Tag
has got the following fields, and the offsets given here, are from
0-127.
Field Length Offsets
Tag 3 0-2
Songname 30 3-32
Artist 30 33-62
Album 30 63-92
Year 4 93-96
Comment 30 97-126
Genre 1 127
WARINING- This is just an ugly way of getting metadata and it might not actually be there because the world has moved to id3v2. id3v1 is actually obsolete. Id3v2 is more complex than this, so ideally you should use existing libraries to read id3v2 data from mp3s . Just putting this out there.
You can use apache tika Java API for meta-data parsing from MP3 such as title, album, genre, duraion, composer, artist and etc.. required jars are tika-parsers-1.4, tika-core-1.4.
Sample Program:
package com.parse.mp3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AudioParser {
/**
* #param args
*/
public static void main(String[] args) {
String fileLocation = "G:/asas/album/song.mp3";
try {
InputStream input = new FileInputStream(new File(fileLocation));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
// List all metadata
String[] metadataNames = metadata.names();
for(String name : metadataNames){
System.out.println(name + ": " + metadata.get(name));
}
// Retrieve the necessary info from metadata
// Names - title, xmpDM:artist etc. - mentioned below may differ based
System.out.println("----------------------------------------------");
System.out.println("Title: " + metadata.get("title"));
System.out.println("Artists: " + metadata.get("xmpDM:artist"));
System.out.println("Composer : "+metadata.get("xmpDM:composer"));
System.out.println("Genre : "+metadata.get("xmpDM:genre"));
System.out.println("Album : "+metadata.get("xmpDM:album"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
For J2ME(which is what I was struggling with), here's the code that worked for me..
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.MetaDataControl;
import javax.microedition.midlet.MIDlet;
public class MetaDataControlMIDlet extends MIDlet implements CommandListener {
private Display display = null;
private List list = new List("Message", List.IMPLICIT);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Alert alert = new Alert("Message");
private Player player = null;
public MetaDataControlMIDlet() {
display = Display.getDisplay(this);
alert.addCommand(exitCommand);
alert.setCommandListener(this);
list.addCommand(exitCommand);
list.setCommandListener(this);
//display.setCurrent(list);
}
public void startApp() {
try {
FileConnection connection = (FileConnection) Connector.open("file:///e:/breathe.mp3");
InputStream is = null;
is = connection.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.prefetch();
player.realize();
} catch (Exception e) {
alert.setString(e.getMessage());
display.setCurrent(alert);
e.printStackTrace();
}
if (player != null) {
MetaDataControl mControl = (MetaDataControl) player.getControl("javax.microedition.media.control.MetaDataControl");
if (mControl == null) {
alert.setString("No Meta Information");
display.setCurrent(alert);
} else {
String[] keys = mControl.getKeys();
for (int i = 0; i < keys.length; i++) {
list.append(keys[i] + " -- " + mControl.getKeyValue(keys[i]), null);
}
display.setCurrent(list);
}
}
}
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exitCommand) {
notifyDestroyed();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Categories