this is my code for split single PDF in a several PDF splitted by page:
public static String splitAndRenamePdf(InputStream file, String targetDir) {
try {
PdfReader reader = new PdfReader(file);
int n = reader.getNumberOfPages();
for (int i=1; i <= n; i++) {
Document document = new Document(reader.getPageSizeWithRotation(i)); //I tried with 1 too
PdfCopy writer = new PdfCopy(document, new FileOutputStream(targetDir+File.separatorChar+i+".pdf"));
document.open();
PdfImportedPage page = writer.getImportedPage(reader, i);
writer.addPage(page);
document.close();
writer.close();
}
return "from 01 to "+n;
} catch (IOException | DocumentException exc) {
System.out.println("splitAndRenamePdf Exception: "+exc.getMessage());
return null;
}
}
the content is right but the resulting n files are each the same size as the original.
Someone could help me? I could change library because I'm not legacy with iText.
I write the solution...
I hope it could help someone.
private final static RenderListener nopListener = new RenderListener() {
#Override
public void renderText(TextRenderInfo renderInfo) { }
#Override
public void renderImage(ImageRenderInfo renderInfo) { }
#Override
public void endTextBlock() { }
#Override
public void beginTextBlock() { }
};
static class Do implements ContentOperator {
public void invoke(PdfContentStreamProcessor processor, PdfLiteral operator, ArrayList<PdfObject> operands) {
PdfName xobjectName = (PdfName)operands.get(0);
names.add(xobjectName);
}
final List<PdfName> names = new ArrayList<>();
}
private static void fixPdfReader(PdfReader reader) throws IOException {
PdfContentStreamProcessor processor = new PdfContentStreamProcessor(nopListener);
Do doOp = new Do();
processor.registerContentOperator("Do", doOp);
int totPages = reader.getNumberOfPages();
for (int page = 1; page <= totPages; page++) {
PdfDictionary resources = reader.getPageResources(page);
if (resources == null) {
System.out.printf("!!! page %d has no resources\n", page);
continue;
}
doOp.names.clear();
processor.processContent(ContentByteUtils.getContentBytesForPage(reader, page), resources);
PdfDictionary newResources = new PdfDictionary();
newResources.putAll(resources);
PdfDictionary xobjects = newResources.getAsDict(PdfName.XOBJECT);
PdfDictionary newXobjects = new PdfDictionary();
for (PdfName key: doOp.names) {
newXobjects.put(key, xobjects.get(key));
}
newResources.put(PdfName.XOBJECT, newXobjects);
reader.getPageN(page).put(PdfName.RESOURCES, newResources);
}
reader.removeUnusedObjects();
}
public static String fixAndSplitPDF(InputStream inputStream, String targetDir) {
try {
PdfReader reader = new PdfReader(inputStream);
fixPdfReader(reader);
//this method is in the question!
return splitAndRenamePdf(reader, targetDir);
} catch (IOException exc) {
//LOG Exception...
return null;
}
}
Related
I'm using Encog and I ran the ocr sample. It works fine. However, I want to pass an image file (png, jpg,...) as a parameter. This image contains the text to to be recognized. Then, the system should return a string with the "same" text.
Has someone already did something similar? How should I start?
Thanks!
Step 1: In GUI create file input and take file from user
JFileChooser fc;
JButton b, b1;
JTextField tf;
FileInputStream in;
Socket s;
DataOutputStream dout;
DataInputStream din;
int i;
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == b) {
int x = fc.showOpenDialog(null);
if (x == JFileChooser.APPROVE_OPTION) {
fileToBeSent = fc.getSelectedFile();
tf.setText(f1.getAbsolutePath());
b1.setEnabled(true);
} else {
fileToBeSent = null;
tf.setText(null;);
b1.setEnabled(false);
}
}
if (e.getSource() == b1) {
send();
}
} catch (Exception ex) {
}
}
public void copy() throws IOException {
File f1 = fc.getSelectedFile();
tf.setText(f1.getAbsolutePath());
in = new FileInputStream(f1.getAbsolutePath());
while ((i = in.read()) != -1) {
System.out.print(i);
}
}
public void send() throws IOException {
dout.write(i);
dout.flush();
}
Step 2: Down sample it
private void processNetwork() throws IOException {
System.out.println("Downsampling images...");
for (final ImagePair pair : this.imageList) {
final MLData ideal = new BasicMLData(this.outputCount);
final int idx = pair.getIdentity();
for (int i = 0; i < this.outputCount; i++) {
if (i == idx) {
ideal.setData(i, 1);
} else {
ideal.setData(i, -1);
}
}
final Image img = ImageIO.read(fc.getFile());
final ImageMLData data = new ImageMLData(img);
this.training.add(data, ideal);
}
final String strHidden1 = getArg("hidden1");
final String strHidden2 = getArg("hidden2");
this.training.downsample(this.downsampleHeight, this.downsampleWidth);
final int hidden1 = Integer.parseInt(strHidden1);
final int hidden2 = Integer.parseInt(strHidden2);
this.network = EncogUtility.simpleFeedForward(this.training
.getInputSize(), hidden1, hidden2,
this.training.getIdealSize(), true);
System.out.println("Created network: " + this.network.toString());
}
Step 3: Begin Training with training set
private void processTrain() throws IOException {
final String strMode = getArg("mode");
final String strMinutes = getArg("minutes");
final String strStrategyError = getArg("strategyerror");
final String strStrategyCycles = getArg("strategycycles");
System.out.println("Training Beginning... Output patterns="
+ this.outputCount);
final double strategyError = Double.parseDouble(strStrategyError);
final int strategyCycles = Integer.parseInt(strStrategyCycles);
final ResilientPropagation train = new ResilientPropagation(this.network, this.training);
train.addStrategy(new ResetStrategy(strategyError, strategyCycles));
if (strMode.equalsIgnoreCase("gui")) {
TrainingDialog.trainDialog(train, this.network, this.training);
} else {
final int minutes = Integer.parseInt(strMinutes);
EncogUtility.trainConsole(train, this.network, this.training,
minutes);
}
System.out.println("Training Stopped...");
}
Step 4: Give down sampled file to neural network
public void processWhatIs() throws IOException {
final String filename = getArg("image");
final File file = new File(filename);
final Image img = ImageIO.read(file);
final ImageMLData input = new ImageMLData(img);
input.downsample(this.downsample, false, this.downsampleHeight,
this.downsampleWidth, 1, -1);
final int winner = this.network.winner(input);
System.out.println("What is: " + filename + ", it seems to be: "
+ this.neuron2identity.get(winner));
}
Step 5: Check Result
I have a given Canvas class, I want to load a Sprite with a special celltype and then draw it on my Canvas. I'm new to GUI and Canvas modelling, with the part of Code below I always get an "Unhandled type IO Exception Error " in line 3 where I Implement my sprite loader. I can easily draw Rectangles and else but I fail at loading my Sprite and convert it to an Image.
private class Canvas extends JPanel {
private static final long serialVersionUID = 1L;
public SpritesheetLoader SL=SpritesheetLoader.defaultLoader();
private Spritesheet S=SL.getSpritesheet("graphics/sprites/equipment/chest/tnecksweater-female");
Image I=S.getCel(0);
/**
* Creates a new canvas object
*/
public Canvas() {
super(true);
super.setBackground(new Color(0, 128, 0)); // middle green
}
/**
* Redraws the canvas
*
* #param g The graphics context to redraw with
*/
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
synchronized (UIPanel.this) {
if (canvasDrawer != null) {
canvasDrawer.draw(g);
}
}
g.drawImage(I, 10, 10, this);
}
}
Edit:
public class SpritesheetLoader {
private String filename;
private Map<String, ZipEntry> spritesheets = null;
// XML parser
private DocumentBuilder xmlParser = null;
private ZipFile zipFile;
public SpritesheetLoader(String filename) {
this.filename = filename;
try {
this.xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException exn) {
throw new RuntimeException(exn);
}
}
#SuppressWarnings("unused")
private static void printDocument(Document doc, OutputStream out) {
// code by http://stackoverflow.com/users/203907/bozho
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, "UTF-8")));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void init() throws IOException {
if (spritesheets != null) {
return;
}
spritesheets = new HashMap<>();
this.zipFile = new ZipFile(this.filename);
Enumeration<? extends ZipEntry> zipIterator = zipFile.entries();
while (zipIterator.hasMoreElements()) {
ZipEntry z = zipIterator.nextElement();
if (z.getName().endsWith(".xml")) {
String name = z.getName().substring(0, z.getName().length() - 4);
spritesheets.put(name, z);
}
}
}
public Spritesheet getSpritesheet(String name) {
ZipEntry entry = spritesheets.get(name);
if (entry == null) {
return null;
}
SpritesheetParser parser = new SpritesheetParser();
parser.parseToplevel(getData(entry));
return parser.getSpritesheet();
}
private InputStream getData(ZipEntry entry) {
try {
InputStream s = zipFile.getInputStream(entry);
return s;
} catch (IOException exn) {
throw new RuntimeException(exn);
}
}
private InputStream getDataForFilename(String data) {
try {
ZipEntry entry = zipFile.getEntry(data);
if (entry == null) {
throw new RuntimeException("Missing file entry: " + data);
}
InputStream s = zipFile.getInputStream(entry);
return s;
} catch (IOException exn) {
throw new RuntimeException(exn);
}
}
public Set<? extends String> getSpritesheetNames() {
return spritesheets.keySet();
}
private static SpritesheetLoader DEFAULT = null;
public static SpritesheetLoader defaultLoader() throws IOException {
if (DEFAULT != null) {
return DEFAULT;
}
DEFAULT = new SpritesheetLoader(System.getProperty("user.home") + File.separator + "prgpr" + File.separator + "graphics.zip");
DEFAULT.init();
return DEFAULT;
}
public static void main(String[] args) throws IOException {
SpritesheetLoader loader = defaultLoader();
System.out.println(loader.getSpritesheetNames());
System.out.println(loader.getSpritesheet("graphics/sprites/equipment/chest/tnecksweater-female"));
}
private class SpritesheetParser {
private Spritesheet spritesheet;
public Spritesheet getSpritesheet() {
return spritesheet;
}
public Element parseDoc(InputStream indoc) {
Document doc;
try {
doc = xmlParser.parse(indoc);
} catch (SAXException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return doc.getDocumentElement();
}
public Element includeIfNeeded(Element elt) {
if (elt.getTagName().equals("include")) {
return parseDoc(getDataForFilename(elt.getAttribute("file")));
}
return null;
}
private void parseImageSet(Element elt) {
if (spritesheet != null) { // already have a spritesheet; obey override semantics
return;
}
String filename = elt.getAttribute("src");
EnumSet<DyeChannel> dyeChannels = EnumSet.noneOf(DyeChannel.class);
int splitIndex;
if ((splitIndex = filename.indexOf('|')) > 0) {
int index = splitIndex + 1;
for (; index < filename.length(); index++) {
switch (filename.charAt(index)) {
case 'R': dyeChannels.add(DyeChannel.RED); break;
case 'G': dyeChannels.add(DyeChannel.GREEN); break;
case 'B': dyeChannels.add(DyeChannel.BLUE); break;
case 'C': dyeChannels.add(DyeChannel.CYAN); break;
case 'M': dyeChannels.add(DyeChannel.MAGENTA); break;
case 'Y': dyeChannels.add(DyeChannel.YELLOW); break;
case 'W': dyeChannels.add(DyeChannel.WHITE); break;
}
}
filename = filename.substring(0, splitIndex);
}
BufferedImage bufferedImage;
try {
bufferedImage = ImageIO.read(getDataForFilename(filename));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
spritesheet = new Spritesheet(bufferedImage, dyeChannels);
if (elt.hasAttribute("width") && elt.hasAttribute("height")) {
spritesheet.setCelDimensions(Integer.parseInt(elt.getAttribute("width")), Integer.parseInt(elt.getAttribute("height")));
}
}
int intAttribute(Element elt, String name) {
if (elt.hasAttribute(name)) {
return Integer.parseInt(elt.getAttribute(name));
}
return 0;
}
private void parseAnimation(Element elt, String name) {
Direction direction = Direction.DEFAULT;
switch (elt.getAttribute("direction")) {
case "up": direction = Direction.UP; break;
case "down": direction = Direction.DOWN; break;
case "left": direction = Direction.LEFT; break;
case "right": direction = Direction.RIGHT; break;
}
Animation animation = new Animation();
boolean looping = true;
NodeList nl = elt.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element) {
Element animationStep = (Element)n;
int xoffset = intAttribute(animationStep, "offsetX");
int yoffset = intAttribute(animationStep, "offsetY");
switch (animationStep.getTagName()) {
case "frame":
int index = intAttribute(animationStep, "index");
animation.addCelSequence(new CelSequence(
index, index, intAttribute(animationStep, "delay")).setOffsets(xoffset, yoffset));
break;
case "sequence":
animation.addCelSequence(new CelSequence(
intAttribute(animationStep, "start"),
intAttribute(animationStep, "end"),
intAttribute(animationStep, "delay")).setOffsets(xoffset, yoffset));
case "end":
looping = false;
break;
}
}
}
animation.setIsLooping(looping);
spritesheet.addAnimation(name, direction, animation);
}
private void parseAction(Element elt) {
String actionName = elt.getAttribute("name");
NodeList nl = elt.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element) {
Element actionPart = (Element)n;
switch (actionPart.getTagName()) {
case "animation": parseAnimation(actionPart, actionName); break;
}
}
}
}
public void parseToplevel(InputStream docStream) {
parseToplevelElement(parseDoc(docStream));
}
public void parseToplevelElement(Element body) {
if (body == null) {
return;
}
if (!body.getTagName().equals("sprite")) {
System.err.println("Not a <sprite>");
return;
}
NodeList nl = body.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element) {
Element elt = (Element) n;
switch (elt.getTagName()) {
case "imageset":
parseImageSet(elt);
break;
case "action":
parseAction(elt);
break;
case "include":
parseToplevelElement(includeIfNeeded(elt));
}
}
}
}
}
}
I want to create image from first page of an PDF . I am using iText in java . Can you suggest me what to do to extract first page of an pdf as an image ?
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(
document, new FileOutputStream(RESULT));
document.open();
File extStore = Environment.getExternalStorageDirectory();
String path=extStore.getPath()+"/FirstPdf.pdf";
PdfReader reader = new PdfReader(path);
int n = reader.getNumberOfPages();
PdfImportedPage page;
for (int i = 1; i <= n; i++) {
page = writer.getImportedPage(reader, i);
// Image.getInstance(page) ;
}
document.close();
I have written the above code . What to do to extract first page of a pdf as an image and save it in SDCARD ?
iText doesn't work for that purpose.
http://www.java2s.com/Open-Source/Android_Free_Code/Pdf/Download_Free_code_Android_Pdf_Viewer_Library.htm
The jar file is in the zip.
Download that library PdfViewer.jar and try this code:
byte[] bytes;
try {
File file = new File("/storage/extSdCard/Test.pdf");
FileInputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
ByteBuffer buffer = ByteBuffer.NEW(bytes);
String data = Base64.encodeToString(bytes, Base64.DEFAULT);
PDFFile pdf_file = new PDFFile(buffer);
PDFPage page = pdf_file.getPage(2, true);
RectF rect = new RectF(0, 0, (int) page.getBBox().width(),
(int) page.getBBox().height());
Bitmap image = page.getImage((int)rect.width(), (int)rect.height(), rect);
FileOutputStream os = new FileOutputStream("/storage/extSdCard/pdf.jpg");
image.compress(Bitmap.CompressFormat.JPEG, 80, os);
//((ImageView) findViewById(R.id.testView)).setImageBitmap(image);
} catch (Exception e) {
e.printStackTrace();
}
You can change the rect around to make it extract any part of the pdf you want etc too, pretty good. Spent about 16 hours banging my head against a wall before finding that solution. Wasn't really sure if it was possible without the swing awt library. Sorry the storage is hard coded but it was the least of my concerns at the time.
I ended up finding out how to do what the question initially asked!!!
You need iTextG library (itextg-5.5.3.jar), scpkix-jdk15on.1.47.0.1.jar & scprov-jdk15on-1.47.0.2.jar
inside where want to call it from:
public static final String RESULT = "/storage/sdcard0/dirAtExtStorage/Img%s.%s";
public void extractImages(String filename)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(filename);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
MyImageRenderListener listener = new MyImageRenderListener(RESULT);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
parser.processContent(i, listener);
}
}
inside MyImageRendererListener.java:
public class MyImageRenderListener implements RenderListener{
private String path;
public MyImageRenderListener(String path) {
this.path = path;
}
#Override
public void beginTextBlock() {
// TODO Auto-generated method stub
}
#Override
public void endTextBlock() {
// TODO Auto-generated method stub
}
public void renderImage(ImageRenderInfo renderInfo) {
try {
System.out.print("renderImage");
String filename;
FileOutputStream os;
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
filename = String.format(path, renderInfo.getRef().getNumber(), image.getFileType());
os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
#Override
public void renderText(TextRenderInfo arg0) {
// TODO Auto-generated method stub
}
}
enjoy guys
Well I have this class for a game I'm making, and I'm trying to save the ArrayList notes. When I logout, it properly print the size, for example if I have 5 notes, when I log out notes.getSize() would be 5, but when I log in, it gets reset back to nothing. Why isn't notes saving?
public class Notes implements Serializable {
private static final long serialVersionUID = -4947870743226160329L;
private ArrayList<Note> notes = new ArrayList<Note>(30);
public class Note implements Serializable {
private static final long serialVersionUID = -4589885080580317958L;
private int color = 0;
private String text = "";
public Note(int color, String text) {
this.setColor(color);
this.setText(text);
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setColor(int color) {
this.color = color;
}
public int getColor() {
return color;
}
}
private transient Player player;
public Notes(Player p) {
this.player = p;
}
public void addNote(String text) {
System.out.println("Note Text: "+text);
if (text.length() > 50) {
player.getPackets().sendGameMessage("You can only enter notes up to 50 characters!");
return;
}
if (notes.size() < 30) {
notes.add(new Note(0, text));
} else {
player.getPackets().sendGameMessage("You cannot add more then 30 notes!");
return;
}
int NoteId = notes.size() - 1;
player.getPackets().sendConfig(1439, NoteId);
player.getTemporaryAttributtes().put("selectedNote", NoteId);
refreshNotes(false);
}
public void addNote(String text, int color) {
notes.add(new Note(color, text));
}
public void loadNotes() {
player.getPackets().sendIComponentSettings(34, 9, 0, 30, 2621470);
player.getPackets().sendHideIComponent(34, 3, false);
player.getPackets().sendHideIComponent(34, 44, false);
player.getPackets().sendIComponentText(34, 13, "Loading notes<br>Please wait...");
player.getPackets().sendConfig(1439, -1);
refreshNotes(true);
}
public void refreshNotes(boolean sendStartConfigs) {
for (int i = 0; i < 30; i++) {
player.getPackets().sendGlobalString(149 + i, i < notes.size() ? notes.get(i).getText() : "");
}
if (sendStartConfigs) {
for (int i = 1430; i < 1450; i++)
player.getPackets().sendConfig(i, i);
}
player.getPackets().sendConfig(1440, getFirstTotalColorValue());
player.getPackets().sendConfig(1441, getSecondTotalColorValue());
}
public int intColorValue(int color, int noteId) {
return (int) (Math.pow(4, noteId) * color);
}
public int getFirstTotalColorValue() {
int Color = 0;
for (int i = 0; i < 15; i++) {
if (notes.size() > i)
Color += intColorValue(notes.get(i).getColor(), i);
}
return Color;
}
public int getSecondTotalColorValue() {
int color = 0;
for (int i = 0; i < 15; i++) {
if (notes.size() > (i + 16))
color += intColorValue(notes.get(i + 16).getColor(), i);
}
return color;
}
public void deleteSelectedNote() {
if ((int)player.getTemporaryAttributtes().get("selectedNote") > -1) {
int slot = (int) player.getTemporaryAttributtes().get("selectedNote");
notes.remove(slot);
player.getTemporaryAttributtes().put("selectedNote", -1);
player.getPackets().sendConfig(1439, -1);
refreshNotes(false);
}
}
public void clear() {
notes.clear();
refreshNotes(false);
}
public void editNote(String string, int index) {
notes.get(index).setText(string);
refreshNotes(false);
}
public void setColor(int color, int index) {
notes.get(index).setColor(color);
refreshNotes(false);
}
public void deleteNote(int slot) {
notes.remove(slot);
refreshNotes(false);
}
public void setNotes(ArrayList<Note> setNotes) {
notes = setNotes;
refreshNotes(false);
}
}
And here is the class I manage saving/loading in
public class SerializableFilesManager {
private static final String PATH = "data/characters/";
private static final String BACKUP_PATH = "data/charactersBackup/";
public synchronized static final boolean containsPlayer(String username) {
return new File(PATH + username + ".p").exists();
}
public synchronized static Player loadPlayer(String username) {
try {
return (Player) loadSerializedFile(new File(PATH + username + ".p"));
} catch (Throwable e) {
Logger.handle(e);
}
try {
Logger.log("SerializableFilesManager", "Recovering account: "
+ username);
return (Player) loadSerializedFile(new File(BACKUP_PATH + username
+ ".p"));
} catch (Throwable e) {
Logger.handle(e);
}
return null;
}
public static boolean createBackup(String username) {
try {
Utils.copyFile(new File(PATH + username + ".p"), new File(
BACKUP_PATH + username + ".p"));
return true;
} catch (Throwable e) {
Logger.handle(e);
return false;
}
}
public synchronized static void savePlayer(Player player) {
try {
storeSerializableClass(player, new File(PATH + player.getUsername()
+ ".p"));
} catch (ConcurrentModificationException e) {
//happens because saving and logging out same time
} catch (Throwable e) {
Logger.handle(e);
}
}
public static final Object loadSerializedFile(File f) throws IOException,
ClassNotFoundException {
if (!f.exists())
return null;
ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
Object object = in.readObject();
in.close();
return object;
}
public static final void storeSerializableClass(Serializable o, File f)
throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(o);
out.close();
}
private SerializableFilesManager() {
}
}
Do NOT mark Player as transient, cause you are saving it, transient will prevent if from
getting saved, and will bring player to the default value of null, when deserialized.
Have you made the player class serializable ?
Its the Entire object graph that gets serialized or none... the purpose of transient is to make a particular member to be left off during serialization so that, the process of serialization goes smoothly.
For example, Suppose in a game we want to keep the progress of the player and hours of play for that session, but not the starting and ending times. So the starting and ending time can be made transient.
you should save your ArrayList with:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream("filename",false);
out = new ObjectOutputStream(fos);
out.writeObject(notes);
out.close();
System.out.println("Object Persisted");
} catch (IOException ex) {
ex.printStackTrace();
}
and when you open your project, import you Arraylist with:
FileInputStream fos;
try {
fos = new FileInputStream("filename");
ObjectInputStream oos = new ObjectInputStream(fos);
notes=(ArrayList) oos.readObject();
fos.close();
{
catch {
}
Thats because your Player is transient...I've tried to demonstrate your logic on other example...when Player was set to private, serialization has been successful and all data has been loaded back. Otherwise, when transient, Player reference was null, it loads only other serialized fields like int. When theres only a transient Player as field in class, the NullPointerException occurs, but ArrayList has size > 0.
I want to run MinecraftApplet.class inside minecraft.jar in a new JFrame.
However, I am asking on how to do this, because my existing code does not work:
This is StartScript which load the jar urls, then updates class path, and finally starts a thread in GameFrame and adds the createApplet.
public class StartScript implements Runnable{
public ClassLoader classLoader;
public boolean natives_loaded;
protected URL[] urlList;
public void run()
{
try
{
String path = (String)AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws Exception {
return InfiniLauncherUtils.getWorkingDirectory() + File.separator + "bin" + File.separator;
}});
File dir = new File(path);
if (!dir.exists())
{
dir.mkdirs();
}
loadJarURLs();
updateClassPath(dir);
Thread start = new Thread(new InfiniLauncherGameFrame(createApplet()));
start.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Applet createApplet() throws InstantiationException, IllegalAccessException, ClassNotFoundException
{
Class appletClass = classLoader.loadClass("net.minecraft.client.MinecraftApplet");
return (Applet)appletClass.newInstance();
}
protected void updateClassPath(File dir)throws Exception
{
URL[] urls = new URL[this.urlList.length];
for (int i = 0; i < this.urlList.length; i++) {
urls[i] = new File(dir, getJarName(this.urlList[i])).toURI().toURL();
System.out.println(urlList[i]);
}
if (classLoader == null) {
classLoader = new URLClassLoader(urls) {
protected PermissionCollection getPermissions(CodeSource codesource)
{
PermissionCollection perms = null;
try
{
Method method = SecureClassLoader.class.getDeclaredMethod("getPermissions", new Class[] { CodeSource.class });
method.setAccessible(true);
perms = (PermissionCollection)method.invoke(getClass().getClassLoader(), new Object[] {
codesource });
String host = "www.minecraft.net";
if ((host != null) && (host.length() > 0))
{
perms.add(new SocketPermission(host, "connect,accept"));
} else codesource.getLocation().getProtocol().equals("file");
perms.add(new FilePermission("<<ALL FILES>>", "read"));
}
catch (Exception e)
{
e.printStackTrace();
}
return perms;
}
};
}
String path = dir.getAbsolutePath();
if (!path.endsWith(File.separator)) path = path + File.separator;
unloadNatives(path);
System.setProperty("org.lwjgl.librarypath", path + "natives");
System.setProperty("net.java.games.input.librarypath", path + "natives");
natives_loaded = true;
}
protected void loadJarURLs() throws Exception {
String jarList[] = {"lwjgl.jar", "jinput.jar", "lwjgl_util.jar", LoginScript.mainGameURL};
//StringTokenizer jar = new StringTokenizer(jarList, ", ");
int jarCount = jarList.length+1;
this.urlList = new URL[jarCount];
URL path = new URL("http://s3.amazonaws.com/MinecraftDownload/");
for (int i = 0; i < jarCount - 1; i++) {
this.urlList[i] = new URL(path, jarList[i]);
System.out.println(urlList[i]);
}
String osName = System.getProperty("os.name");
String nativeJar = null;
if (osName.startsWith("Win"))
nativeJar = "windows_natives.jar.lzma";
else if (osName.startsWith("Linux"))
nativeJar = "linux_natives.jar.lzma";
else if (osName.startsWith("Mac"))
nativeJar = "macosx_natives.jar.lzma";
else if ((osName.startsWith("Solaris")) || (osName.startsWith("SunOS")))
nativeJar = "solaris_natives.jar.lzma";
else {
}
if (nativeJar == null) {
} else {
this.urlList[(jarCount - 1)] = new URL(path, nativeJar);
}
}
protected String getJarName(URL url)
{
System.out.println(url);
String fileName = url.toString();
if (fileName.contains("?"))
{
fileName = fileName.substring(0, fileName.indexOf("?"));
}
if (fileName.endsWith(".pack.lzma"))
{
fileName = fileName.replaceAll(".pack.lzma", "");
}
else if (fileName.endsWith(".pack"))
{
fileName = fileName.replaceAll(".pack", "");
}
else if (fileName.endsWith(".lzma"))
{
fileName = fileName.replaceAll(".lzma", "");
}
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
private void unloadNatives(String nativePath)
{
if (!natives_loaded) {
return;
}
try
{
Field field = ClassLoader.class.getDeclaredField("loadedLibraryNames");
field.setAccessible(true);
Vector libs = (Vector)field.get(getClass().getClassLoader());
String path = new File(nativePath).getCanonicalPath();
for (int i = 0; i < libs.size(); i++) {
String s = (String)libs.get(i);
if (s.startsWith(path)) {
libs.remove(i);
i--;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
GameFrame class
public InfiniLauncherGameFrame(Applet aapplet)
{
applet = aapplet;
System.out.println("ran");
}
public void run()
{
System.out.println("few");
removeAll();
add(applet);
validate();
setVisible(true);
setSize(300, 300);
}
I do not get any errors when I run it, however the new frame is black with a small white box at the top left.
Picture Here: http://imgur.com/rJjqC
I might not be getting errors because I thrown away a couple of exceptions.
Any help is much appreciated.
Maybe a stupid suggestion, but could it be because you didn't explicitly call the repaint() method? That happens to me a lot