How to search an element in a property file? - java

The requirement is:
Invoice number will be passed from the XSLT, based on the invoice number I must increment the counter corresponding to that invoice number.
Example: invoice=1020 is passed from XSLT, I must read that invoice and search in a file whether it is present or not. If yes, increment counter (count=prev_count+1).
If not, write the invoice number in the file and initialize it to 1.
How to acheive this requirement?
Thanks in advance.
public static void LookupInsert( int invoiceNumber)
{
Properties properties = new Properties();
File propertiesfile = new File("Sequence.properties");
if(propertiesfile.length()==0)
{
try{
propertiesfile.createNewFile();
properties.load(new FileInputStream(propertiesfile));
} catch (IOException e) {
e.printStackTrace();
}
int value=1;
properties.setProperty(new Integer(invoiceNumber).toString(), new Integer(value).toString());
}
try {
propertiesfile.createNewFile();
properties.load(new FileInputStream(propertiesfile));
} catch (IOException e) {
e.printStackTrace();
}
Properties props = System.getProperties();
if(props.get(invoiceNumber)== null)
{
int value=1;
props.setProperty(new Integer(invoiceNumber).toString(), new Integer(value).toString());
try {
properties.store(new FileOutputStream(propertiesfile), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
int value = Integer.parseInt(props.get(invoiceNumber).toString());
value++;
props.setProperty(new Integer(invoiceNumber).toString(), new Integer(value).toString());
try {
properties.store(new FileOutputStream(propertiesfile), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// main() is used for testing
public static void main(String[] a) {
LookupInsert(101);
LookupInsert(101);
LookupInsert(101);
}
}
But the above code is creating file but its not updating value in the file..

Hope below is the code that you are looking for..
public void LookupInsert(int invoiceNumber)
{
Properties props = System.getProperties();
//if there is no invoice number in properties file then get(invoiceNumber) will be null
if(props.get(invoiceNumber)== null)
props.setProperty(new Integer(invoiceNumber).toString(), new Integer(1).toString());
else
{
int value = Integer.parseInt(props.get(invoiceNumber).toString());
value++;
props.setProperty(new Integer(invoiceNumber).toString(), new Integer(value).toString());
}
File file =new File("test.properties");
FileWriter fw = new FileWriter(file);
props.store(fw,"");
fw.close();
}

Related

Increment number every time program runs

I want to increment the count every time my program runs. I tried running below code but it keeps on printing 1 every time i run the program. Also anything special i need to do to increase the date.
public class CounterTest {
int count = 0;
public static void main(String[] args) {
CounterTest test1 = new CounterTest();
test1.doMethod();
}
public void doMethod() {
count++;
System.out.println(count);
}
}
You could simply create a properties file for your application to keep track of such things and application configuration details. This of course would be a simple text file containing property names (keys) and their respective values.
Two small methods can get you going:
The setProperty() Method:
With is method you can create a properties file and apply whatever property names and values you like. If the file doesn't already exist then it is automatically created at the file path specified:
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
outputStream.close();
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
If you don't already contain a specific properties file then it would be a good idea to call the above method as soon as the application starts (perhaps after initialization) so that you have default values to play with if desired, for example:
if (!new File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
The above code checks to see if the properties file named config.properties already exists (you should always use the .properties file name extension). If it doesn't then it is created and the property name (Key) is applied to it along with the supplied value for that property. Above we are creating the ApplicationRunCount property which is basically for your specific needs. When you look into the config.properties file created you will see:
#Mon Sep 28 19:07:08 PDT 2020
ApplicationRunCount=0
The getProperty() Method:
This method can retrieve a value from a specific property name (key). Whenever you need the value from a particular property contained within your properties file then this method can be used:
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
Your Task:
What is confusing here is you say you want to keep track of the number of times your Program is run yet you increment your counter variable named count within a method named doMethod(). This would work if you can guarantee that this method will only run once during the entire time your application runs. If this will indeed be the case then you're okay. If it isn't then you would possibly get a count total that doesn't truly represent the actual number of times your application was started.
In any case, with the scheme you're currently using, you could do this:
public class CounterTest {
// Class Constructor
public CounterTest() {
/* If the config.properties file does not exist
then create it and apply the ApplicationRunCount
property with the value of 0. */
if (!new java.io.File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
}
public static void main(String[] args) {
new CounterTest().doMethod(args);
}
private void doMethod(String[] args) {
int count = Integer.valueOf(getProperty("config.properties",
"ApplicationRunCount"));
count++;
setProperty("config.properties", "ApplicationRunCount",
String.valueOf(count));
System.out.println(count);
}
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new
java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
}
Whenever you start your application you will see the run count within the Console Window. Other useful methods might be removeProperty() and renameProperty(). Here they are:
/**
* Removes (deletes) the supplied property name from the supplied property
* file.<br>
*
* #param propertiesFilePath (String) The full path and file name of the
* properties file you want to remove a property name from.<br>
*
* #param propertyName (String) The property name you want to remove from
* the properties file.<br>
*
* #return (Boolean) Returns true if successful and false if not.
*/
public static boolean removeProperty(String propertiesFilePath,
String propertyName) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(propertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(propertiesFilePath)) {
prop.store(out, null);
return true;
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return false;
}
/**
* Renames the supplied property name within the supplied property file.<br>
*
* #param propertiesFilePath (String) The full path and file name of the
* properties file you want to rename a property in.<br>
*
* #param oldPropertyName (String) The current name of the property you want
* to rename.<br>
*
* #param newPropertyName (String) The new property name you want to use.<br>
*
* #return (Boolean) Returns true if successful and false if not.
*/
public static boolean renameProperty(String propertiesFilePath, String oldPropertyName,
String newPropertyName) {
String propertyValue = getProperty(propertiesFilePath, oldPropertyName);
if (propertyValue == null) { return false; }
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(oldPropertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false ;}
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(propertiesFilePath)) {
prop.store(out, null);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
return setProperty(propertiesFilePath, newPropertyName, propertyValue);
}
Try this.
public class CounterTest {
static final Path path = Path.of("counter.txt");
int count;
CounterTest() throws IOException {
try {
count = Integer.valueOf(Files.readString(path));
} catch (NoSuchFileException | NumberFormatException e) {
count = 0;
}
}
public void doMethod() throws IOException {
++count;
System.out.println(count);
Files.writeString(path, "" + count);
}
public static void main(String[] args) throws IOException {
CounterTest c = new CounterTest();
c.doMethod();
}
}
You can't the only way is to use a Database or simpler use a txt file to save the number and every time you run your app reads the txt file and gets the number.
Here is How to do it:
This is the Main class:
package main;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String path = "C:\\Example.txt";
int number = 0;
try {
ReadFile file = new ReadFile(path);
String[] aryLines = file.OpenFile();
try {
number = Integer.parseInt(aryLines[0]);
} catch (Exception e) {
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(number);
number++;
File txtfile = new File(path);
if (txtfile.exists()) {
txtfile.delete();
try {
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
} else {
try {
System.out.println("no yei");
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
}
}
}
the class that writes anything you need:
package main;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteFile {
public String path;
public boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textline) throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textline);
print_line.close();
}
}
And this one is the one that gets the text on the file:
package main;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private static String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int j = 0; j < numberOfLines; j++) {
textData[j] = textReader.readLine();
}
textReader.close();
return textData;
}
static int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}

Operations on file with multithreading

I'm trying to work with multiThreading and I want to write a code that must do some operations on a specific file called data.txt.
There must be three writers and three readers,writer 1 has to write a random char from A to Z,writer 2 has to write a random number from 1 to 100,writer 3 has to write a random char from this set of characters {*%$##!&}.
Then readers must read a character from the file data.txt and then reader 1 write this character in file 1.txt,reader 2 write this character in file 2.txt and reader 3 write this character in file 3.txt.
If there was no character in data file to read the readers must wait until the writers add something to the data file.
I have wrote two classes called WriterInFile and ReaderFromFile that extends Thread class but it seems that the ReaderFromFile doesn't work correctly(It doesn't read any characters from data file and doesn't add anything to files 1.txt,2.txt,3.txt)
This is the code for ReaderFromFile class:
import java.io.*;
public class ReaderFromFile extends Thread {
private static FileReader reader;
private int numberOfReader;
ReaderFromFile(int numberOfReader, FileReader reader) {
this.numberOfReader = numberOfReader;
ReaderFromFile.reader = reader;
}
public void run() {
for (int i = 0; i < 5; i++) {
String s = null;
try {
s = readFrom();
} catch (IOException e) {
e.printStackTrace();
}
FileWriter writer;
switch (numberOfReader) {
case 1:
try {
writer = new FileWriter("1.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 2:
try {
writer = new FileWriter("2.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 3:
try {
writer = new FileWriter("3.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/**
* #return the character that has been reed
*/
private synchronized String readFrom() throws IOException {
String s = null;
while (!reader.ready()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
s = String.valueOf(reader.read());
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
return s;
}
}
this is the WriterInFile class:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class WriterInFile extends Thread {
private static FileWriter writer;
private int numberOfReader;
WriterInFile(int numberOfReader, FileWriter writer) {
this.numberOfReader = numberOfReader;
WriterInFile.writer = writer;
}
public void run() {
for (int i=0;i<5;i++){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (numberOfReader) {
case 1:
writeChar();
break;
case 2:
writeNumber();
break;
case 3:
writeShape();
break;
}
}
}
private synchronized void writeChar() {
String s = getRandomChar();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private synchronized void writeNumber() {
String s = getRandomNumber();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private synchronized void writeShape() {
String s = getRandomShape();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private String getRandomChar() {
double randomDouble = Math.random();
randomDouble = randomDouble * 26;
int randomInt = (int) randomDouble;
return String.valueOf((char)(randomInt+'A'));
}
private String getRandomNumber() {
double randomDouble = Math.random();
randomDouble = randomDouble * 100 + 1;
int randomInt = (int) randomDouble;
return String.valueOf(randomInt);
}
private String getRandomShape() {
String chars = "*%$##!&";
Random rnd = new Random();
char randomChar = chars.charAt(rnd.nextInt(chars.length()));
return String.valueOf(randomChar);
}
}
and this is the main file:
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("data.txt");
FileReader reader = new FileReader("data.txt");
//creating writers
WriterInFile writer1 = new WriterInFile(1, writer);
WriterInFile writer2 = new WriterInFile(2, writer);
WriterInFile writer3 = new WriterInFile(3, writer);
// creating readers
ReaderFromFile reader1 = new ReaderFromFile(1, reader);
ReaderFromFile reader2 = new ReaderFromFile(2, reader);
ReaderFromFile reader3 = new ReaderFromFile(3, reader);
writer1.start();
writer2.start();
writer3.start();
reader1.start();
reader2.start();
reader3.start();
Thread.sleep(10000);
writer.close();
reader.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}

NoSuchElementException Scanner not waiting

I am working on my first server project for school and I am receiving a NoSuchElementException when reaching the code below in my client. From my understanding, the way I have written it, the scanner should be waiting for the server to send back a string. Instead it seems to be jumping right to the exception. In the server code (second below) I have the output that is supposed to return all strings in an array. My goal is to have the client print all of the strings in the text area (status).
static void runClient() {
Socket client = null;
PrintWriter output = null;
Scanner input = null;
try {
client = new Socket("localhost", 5007);
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream());
output.println(game);
output.println(numberOfPicks);
output.flush();
pStr("Data Sent");
while (true) {
pStr("Waiting for Server");
status.appendText(input.nextLine());
if (!input.hasNext())
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (Exception e) {
}
try {
output.close();
} catch (Exception e) {
}
try {
client.close();
} catch (Exception e) {
}
}
}
private static void pStr(String string) {
System.out.println(string);
}
}
PARTIAL SERVER CODE BELOW
public void run() {
PrintWriter output = null;
Scanner input = null;
try {
// Get input and output streams.]
input = new Scanner(connection.getInputStream());
output = new PrintWriter(connection.getOutputStream());
String game;
int quickPicks;
try {
game = input.nextLine();
quickPicks = Integer.parseInt(input.nextLine());
switch (game) {
case "PowerBall":
ansStr = new pickNumbers(game, quickPicks, 69, 26).getQuickPicks();
break;
case "MegaMillions":
ansStr = new pickNumbers(game, quickPicks, 70, 25).getQuickPicks();
break;
case "Lucky4Life":
ansStr = new pickNumbers(game, quickPicks, 48, 18).getQuickPicks();
break;
default:
throw new RuntimeException("Incorrect Game");
}
} catch (Exception e) {
output.println(e.getMessage());
}
for (int i = 0; i < ansStr.length; i++) {
output.println(ansStr[i]);
//output.flush();
}
} catch (Exception e) {
pStr(e.getMessage());
} finally {
try {
input.close();
} catch (Exception e) {
}
try {
output.close();
} catch (Exception e) {
}
try {
connection.close();
} catch (Exception e) {
}
}
}
}
How about nesting status.appendText(input.nextLine()); in a test for hasNextLine e.g:
if(input.hasNextLine()){
status.appendText(input.nextLine());
}

Decide cast and return type by Parameter

I really don't know what to look for and if this is even possible. I am trying to code a dynamic Fileloader.
This is the code:
public static Serializable loadSerializable(Context context,
String filename, Object object) {
final String DEBUGTAG = "Loading data" ;
Serializable serializable = null;
ObjectInputStream oin = null;
try {
File file = new File(context.getFilesDir(), filename);
FileInputStream in = new FileInputStream(file);
oin = new ObjectInputStream(in);
Object readElement = oin.readObject();
serializable = (Serializable) readElement; // here I want dynamic casting
Log.d(DEBUGTAG, "Success : " + filename);
} catch (FileNotFoundException e) {
Log.d(DEBUGTAG, "File not found");
} catch (StreamCorruptedException e) {
Log.d(DEBUGTAG, "Stream Corrupted");
} catch (IOException e) {
Log.d(DEBUGTAG, "IOException");
} catch (ClassNotFoundException e) {
Log.d(DEBUGTAG, "Class not Found");
} catch (NullPointerException e) {
Log.d(DEBUGTAG, "NullPointer - File does not exist yet");
} finally {
if (oin != null)
try {
oin.close();
} catch (IOException e) {
Log.d(DEBUGTAG, "IOException - Stream not closed");
}
}
return serializable;
}
What I want to do now is instead of creating a new method for every single object I want to use the 3rd argument (object or whatever) for the type casting.
So I could write
String myString = loadSerializable(this, test.dat, String) or
ArrayList<Fragment> = loadSerializable(this, test.dat, ArrayList<Fragment>) and so on....
Help appreciated
Something like
public static <T> T loadSerializable(Context context, String filename) {
// ...
T t = (T) readElement;
// ...
return t;
}

Deserialize multiple Java Objects

hello dear colleagues,
I have a Garden class in which I serialize and deserialize multiple Plant class objects. The serializing is working but the deserializing is not working if a want to assign it to calling variable in the mein static method.
public void searilizePlant(ArrayList<Plant> _plants) {
try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (int i = 0; i < _plants.size(); i++) {
out.writeObject(_plants.get(i));
}
out.close();
fileOut.close();
} catch (IOException ex) {
}
}
deserializing code:
public ArrayList<Plant> desearilizePlant() {
ArrayList<Plant> plants = new ArrayList<Plant>();
Plant _plant = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
Object object = in.readObject();
// _plant = (Plant) object;
// TODO: ITERATE OVER THE WHOLE STREAM
while (object != null) {
plants.add((Plant) object);
object = in.readObject();
}
in.close();
} catch (IOException i) {
return null;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
return null;
}
return plants;
}
My invoking code:
ArrayList<Plant> plants = new ArrayList<Plant>();
plants.add(plant1);
Garden garden = new Garden();
garden.searilizePlant(plants);
// THIS IS THE PROBLEM HERE
ArrayList<Plant> dp = new ArrayList<Plant>();
dp = garden.desearilizePlant();
edit
I got a null Pointer exception
The solution of #NilsH is working fine, thanks!
How about serializing the entire list instead? There's no need to serialize each individual object in a list.
public void searilizePlant(ArrayList<Plant> _plants) {
try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(_plants);
out.close();
fileOut.close();
} catch (IOException ex) {
}
}
public List<Plant> deserializePlant() {
List<Plants> plants = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
plants = in.readObject();
in.close();
}
catch(Exception e) {}
return plants;
}
If that does not solve your problem, please post more details about your error.
It may not always be feasible to deserialize a whole list of objects (e.g., due to memory issues). In that case try:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
filename));
while (true) {
try {
MyObject o = (MyObject) in.readObject();
// Do something with the object
} catch (EOFException e) {
break;
}
}
in.close();
Or using the Java SE 7 try-with-resources statement:
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(
filename))) {
while (true) {
MyObject o = (MyObject) in.readObject();
// Do something with the object
}
} catch (EOFException e) {
return;
}
If you serialize it to an array linear list, you can cast it back to an array linear list when deserializing it -- all other methods failed for me:
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Program
{
public static void writeToFile(String fileName, Object obj, Boolean appendToFile) throws Exception
{
FileOutputStream fs = null;
ObjectOutputStream os = null;
try
{
fs = new FileOutputStream(fileName);
os = new ObjectOutputStream(fs);
//ObjectOutputStream.writeObject(object) inherently writes binary
os.writeObject(obj); //this does not use .toString() & if you did, the read in would fail
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
os.close();
fs.close();
}
catch(Exception e)
{
//if this fails, it's probably open, so just do nothing
}
}
}
#SuppressWarnings("unchecked")
public static ArrayList<Person> readFromFile(String fileName)
{
FileInputStream fi = null;
ObjectInputStream os = null;
ArrayList<Person> peopleList = null;
try
{
fi = new FileInputStream(fileName);
os = new ObjectInputStream(fi);
peopleList = ((ArrayList<Person>)os.readObject());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch(EOFException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
os.close();
fi.close();
}
catch(Exception e)
{
//if this fails, it's probably open, so just do nothing
}
}
return peopleList;
}
public static void main(String[] args)
{
Person[] people = { new Person(1, 39, "Coleson"), new Person(2, 37, "May") };
ArrayList<Person> peopleList = new ArrayList<Person>(Arrays.asList(people));
System.out.println("Trying to write serializable object array: ");
for(Person p : people)
{
System.out.println(p);
}
System.out.println(" to binary file");
try
{
//writeToFile("output.bin", people, false); //serializes to file either way
writeToFile("output.bin", peopleList, false); //but only successfully read back in using single cast
} // peopleList = (ArrayList<Person>)os.readObject();
// Person[] people = (Person[])os.readObject(); did not work
// trying to read one at a time did not work either (not even the 1st object)
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("\r\n");
System.out.println("Trying to read object from file. ");
ArrayList<Person> foundPeople = null;
try
{
foundPeople = readFromFile("input.bin");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (foundPeople == null)
{
System.out.println("got null, hummm...");
}
else
{
System.out.println("found: ");
for(int i = 0; i < foundPeople.size(); i++)
{
System.out.println(foundPeople.get(i));
}
//System.out.println(foundPeople); //implicitly calls .toString()
}
}
}

Categories

Resources