Java - Specifically File I/O with objects - java

The exact thing I'm trying to do is to save a 2D array called num into a file called savedNumbers.data. Here is the code for saving to the .data file:
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {
num[0][0] = Integer.parseInt(line00Tf.getText());
num[0][1] = Integer.parseInt(line01Tf.getText());
num[0][2] = Integer.parseInt(line02Tf.getText());
num[0][3] = Integer.parseInt(line03Tf.getText());
num[0][4] = Integer.parseInt(line04Tf.getText());
num[1][0] = Integer.parseInt(line10Tf.getText());
num[1][1] = Integer.parseInt(line11Tf.getText());
num[1][2] = Integer.parseInt(line12Tf.getText());
num[1][3] = Integer.parseInt(line13Tf.getText());
num[1][4] = Integer.parseInt(line14Tf.getText());
num[2][0] = Integer.parseInt(line20Tf.getText());
num[2][1] = Integer.parseInt(line21Tf.getText());
num[2][2] = Integer.parseInt(line22Tf.getText());
num[2][3] = Integer.parseInt(line23Tf.getText());
num[2][4] = Integer.parseInt(line24Tf.getText());
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("savedNumbers.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(num[0]);
oStream.writeObject(num[1]);
oStream.writeObject(num[2]);
JOptionPane.showMessageDialog(null, "File saved OK");
oStream.close();
} catch (IOException e) {
System.out.println("Error writing to file: " + e);
}
}
That code seems to be working well.
Now I want to view all the same numbers one array at a time in JOptionPane, so three lines of saved numbers will show, then OK is pressed and another three lines of saved numbers will show until there are no more.
I am having issues with calling the numbers from savednumbers.data
Here is the code for that:
//CODE FOR CALLING num FROM savedNums.data
private void showSavedNumsBtnActionPerformed(java.awt.event.ActionEvent evt) {
File inFile;
FileInputStream fStream;
ObjectInputStream oStream;
try{
inFile = new File("savedNumbers.data");
fStream = new FileInputStream(inFile);
oStream = new ObjectInputStream(fStream);
ArrayList <LottoPhase1> numList;
numList = (ArrayList<LottoPhase1>)oStream.readObject(); //THIS LINE HAVING PROBLEMS WITH
for(LottoPhase1 ph1:numList){
JOptionPane.showMessageDialog(null,
"Saved numbers " +
"Numbers: " + Arrays.toString(ph1.getNum())
);
}
oStream.close();
}
catch(IOException | ClassNotFoundException e){
JOptionPane.showMessageDialog(null, "Error: " + e);
}
I have also tried calling the ArrayList num, numList, aList, and neither worked.
The class LottoPhase1 is created and runs with no errors, and is fully debugged.

You are writing Arrays to the file, not ArrayList(s). This will not allow you to cast (ArrayList) back from the file because ObjectOutputStream saves the class name of the object with the object to allow it to deserialize it with ObjectInputStream
I would recommend either changing the data type of the object that you are writing to the file to be an ArrayList or to change the data type of the object that you are storing the data from the file in to an Array.

Related

How to load a tsv file for MALLET using FileInputStream in Java?

I want to load the flat text file passed in as 'TMFlatFile' (which is the .tsv file format to use in MALLET) into into the fileReader variable.
I have created the method, RunTopicModelling() and am having a problem with the try/except block.
I have created my File and FileInputStream objects, but dont know how to load it correctly into fileReader?
I have an error that "The method read(CharBuffer) in the type InputStreamReader is not applicable for the arguments (int)".
public class TopicModelling {
private void StartTopicModellingProcess(String filePath) {
JSONIOHelper jsonIO = new JSONIOHelper();
jsonIO.LoadJSON(filePath);
ConcurrentHashMap<String, String> lemmas = jsonIO.GetDocumentsFromJSONStructure();
SaveLemmaDataToFile("topicdata.txt" ,lemmas);
}
private void SaveLemmaDataToFile(String TMFlatFile, ConcurrentHashMap<String, String> lemmas) {
for (Entry<String, String> entry : lemmas.entrySet()) {
try (FileWriter writer = new FileWriter(TMFlatFile)) {
;
writer.write(entry.getKey() + "\ten\t" + entry.getValue() + "\r\n");
} catch (Exception e)
{
System.out.println("Saving to flat text file failed...");
}
}
}
private void RunTopicModelling(String TMFlatFile, int numTopics, int numThreads, int numIterations) {
ArrayList<Pipe> pipeList = new ArrayList <Pipe>();
// Pipes: tokenise, map to features
pipeList.add(new CharSequence2TokenSequence (Pattern.compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}")));
pipeList.add(new TokenSequence2FeatureSequence());
InstanceList instances = new InstanceList (new SerialPipes(pipeList));
InputStreamReader fileReader = null;
//loads the file passed in via the TMFlatFile variable into the fileReader variable - this block I have a problem with
try {
File inFile = new File(TMFlatFile);
FileInputStream fis = new FileInputStream(inFile);
int line;
while ((line = fis.read()) != -1) {
}
fileReader.read(line);
}
fis.close();
}catch(
Exception e)
{
System.out.println("File Load Failed");
System.exit(1);
}
\\ // linking data to the pipeline
instances.addThruPipe(new CsvIterator(fileReader,Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),3,2,1));
}
Can someone tell me what is the correct way to do this?
It's hard to say what the immediate issue is because the code sample provided looks like it's missing important parts, and would not compile as written (for example Exception e) and regex without quotes).
The data import developers guide https://mimno.github.io/Mallet/import-devel has sample code that should be a good starting point.

Reading/Writing object Array to file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to save an array of objects to a file and then to be able to read the objects from that file and add them to an Array. I'm not getting any errors, but it doesn't seem to do anything. I'm not sure if my problem lies in my read or write methods.
Movie allmovies = new Movie[4]
public void writeFile()
{
try
{
FileOutputStream fos = new FileOutputStream("movies.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(allmovies);
oos.close();
System.out.println("File Saved");
}
catch(Exception e) {
System.out.println("Error in output:" + e.toString());
}
}
public void readFile()
{
try
{
FileInputStream fis = new FileInputStream("movies.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Movie[] allmovies = (Movie[]) ois.readObject();
ois.close();
System.out.println("File Imported");
}
catch(Exception e)
{
System.out.println("Error in output:" + e.toString());
}
}
Edit: Also the format of the example file we have been given that we need to read is
Movie Title:
Director:
fileSize:
duration:
I was able to get it to write 1 object and read 1 object but it was in a different format when I view the saved file. Is there anyway to get it in the same format as the example?
Also the format of the example file we have been given that we need to
read is
Movie Title:
Director:
fileSize:
duration:
I was able to get it to write 1 object and read 1 object but it was in
a different format when I view the saved file.
Java serialization allows to encode an object to bytes and not to a textual human understandable representation of the serialized object.
If you want really to write the file in the format you show, you should use :
to write the movies in a textual representation : a BufferedWriter wrapping a FileWriter.
For example : new BufferedWriter(new FileWriter("myFile")).
It has an append(CharSequence) method to append String objects and a newLine() method to append a newline.
to read the movies in a textual representation : A BufferedReader wrapping a FileReader.
For example : new BufferedReader(new FileReader("myFile")).
It has a readLine() method to read a line of the stream.
If you want to serialize movies as bytes and only render them as a textual representation, keep the use of the Java serialization and add a processing to display the Movie array in the required textual format.
After deserializing the array, you just need to iterate on it to generate the required textual representation of the movie.
For example to render the read objects in the standard output, you could write :
Movie[] movies = (Movie[]) ois.readObject();
for (Movie movie : movies){
System.out.println("Movie Title:" + movie.getTitle());
System.out.println("Director:" + movie.getDirector());
System.out.println("fileSize:" + String.valueOf(movie.getTitle()));
System.out.println("duration:" + movie.getTitle());
}
This has been done using arrays without any collections. I modified your code a bit, hope this helps.You can directly copy this code and run. It will successfully read the objects and display all four of them. In a future version which I will upload I will add more commenting to increase the clarity for the same.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Test {
Movie[] allMovies = new Movie[4];
public static void main(String[] args) {
Test t = new Test();
t.allMovies[0] = new Movie("A","B",1L,2L);
t.allMovies[1] = new Movie("C","D",1L,2L);
t.allMovies[2] = new Movie("E","F",1L,2L);
t.allMovies[3] = new Movie("G","H",1L,2L);
t.writeFile();
t.readFile();
}
public void writeFile()
{
try
{
FileOutputStream fos = new FileOutputStream("movies.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(allMovies);
oos.close();
System.out.println("File Saved");
}
catch(Exception e) {
System.out.println("Error in output:" + e.toString());
}
}
public void readFile()
{
try
{
FileInputStream fis = new FileInputStream("movies.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Movie[] allmovies = (Movie[]) ois.readObject();
for(int i = 0; i < 4; i++){
System.out.println("Movie = " + allmovies[i].movieTitle + " Director = " + allmovies[i].director + " FileSize = " + allmovies[i].fileSize + " Duration = " + allmovies[i].duration);
}
ois.close();
System.out.println("File Imported");
}
catch(Exception e)
{
System.out.println("Error in output:" + e.toString());
}
}
}
class Movie implements Serializable{
private static final long serialVersionUID = 1647631086810497694L;
String movieTitle;
String director;
Long fileSize;
Long duration;
Movie(String m, String d, Long fs, Long dur){
this.movieTitle = m;
this.director = d;
this.fileSize = fs;
this.duration = dur;
}
}

Is this correctly writing to a text file?

I am trying to save the integers in an array to a text file. Neither of these seem to be doing the trick while sitting in my main method and I was wondering if someone could point out my mistake.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File ("C:/Users/Usman/Desktop/directory/scores.txt");
PrintWriter writer = new PrintWriter("scores.txt");
writer.println("Player 1 score: " + scorep1[0]);
writer.println("Player 2 score: " + scorep1[1]);
writer.println("Player 3 score: " + scorep1[2]);
writer.println("Player 4 score: " + scorep1[3]);
writer.close();
System.exit(0);
}
No score.txt file is created on my desktop in either of these attempts.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File("C:/Users/Me/Desktop/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
System.exit(0);
}
EDIT: This is what I have made of the answers so far, please feel free to edit the wrong bit so I can clearly see what I've missed.
System.out.println("What's happening");
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
FileWriter fileWriter = new FileWriter(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
Also what about this:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Rather a problem of directory
see this:
How to use PrintWriter and File classes in Java?
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
// NOK for C:/Users see below
// File file = new File("C:/Users/Me/Desktop/file.txt");
File file = new File("C:/classical_dir/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
This works well on my pc:
File file = new File("C:/foo/bar/blurps/file.txt");
This throws an exception: windows seems not to want it
File file = new File("C:/Users/Me/Desktop/file.txt");
because, C:/Users/Me seems to be prohibited: C:/Users seems to be protected by system
see this for writing in User directory: how can I create a file in the current user's home directory using Java?
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
see this also: How to get the Desktop path in java
Because File object does not create a physical copy of a file. For details follow this linkDoes creating a File object create a physical file or touch anything outside the JVM?
Now if we come to your solution then first make a empty file on the disk by following command
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "C:\\Users\\MOSSAD\\Desktop\\new\\temp.txt";
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
File file = new File (fileName);
PrintWriter writer = new PrintWriter(file);
writer.println("Player 1 score: " + 5);
writer.println("Player 2 score: " + 2);
writer.println("Player 3 score: " + 3);
writer.println("Player 4 score: " + 4);
writer.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
you need to use double slash in path .link

How to serialize ArrayList 2x and dont over write the already present ArrayList JAVA

I'm stuck with making an admin panel for my program to serialize more objects, what it does is , it saves object(String,String) into arraylist and the arraylist is saved into file through serialization.
When trying to add another object into the arraylist, The program first deserialize the file stuff into the arraylist, because by not doing this how would i access the objects that are already present in the file.?
but instead something like this happens while adding object 3
(console)
Index 0 [[Word : word1 - Hint : hint1], Word : word2 - Hint : hint2]
how to solve this ?
I think i should delete the old arraylist every time a new a new object is created but i dont know how to do that, is there anything i can do to edit the old arraylist in the file instead of deleting it. Thanks in advance
enter code here
class Admin{
ArrayList al = new ArrayList();
public void ifwordsarepresent(){
try {
FileInputStream fis = new FileInputStream("D:/serial.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
if(fis.available()>0){
try {
try {
al.add((ArrayList) ois.readObject());
addingwords();
ois.close();
} catch
public void addingwords(){
try {
try {
System.out.print("New Word = ");
Scanner scan = new Scanner(System.in);
String word = scan.next();
System.out.print("New hint = ");
Scanner scan2 = new Scanner(System.in);
String hint = scan2.nextLine();
FileOutputStream fos = new FileOutputStream("D:/serial.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Word newword = new Word(word , hint);
al.add(newword);
oos.writeObject(al);
oos.flush();
oos.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}}catch(IOException e) {
System.out.println("Exception during serialization: " + e);
}
MovingForward();
}

Java reading a vector of objects from a file only reads the first object in the vector

I have several objects which are assigned attributes based on user input. I then store those objects in a vector, and then write that vector to a file but on deserializing the stored vector, only the first object is read. Here's the code that i have so far:
public Vector<Cases> registerCase() {
Vector<Cases> casesVector = new Vector<Cases>(10, 2);
Scanner myCase = new Scanner(System.in);
Scanner userChoice = new Scanner(System.in);
System.out.println("HOW MANY CASES DO YOU WANT TO REGISTER?");
int count = userChoice.nextInt();
for (int i = 0; i < count; i++) {
Cases newCase = new Cases();
System.out.println("Enter the case name: ");
newCase.caseName = myCase.nextLine();
System.out.println("Enter the client's name: ");
newCase.client = myCase.nextLine();
System.out.println("Enter the case type: ");
newCase.caseType = myCase.nextLine();
if((newCase.caseType.equals("Major")) || newCase.caseType.equals("major")){
newCase.closedCaseRevenue = majorCasePrice;
}else {
newCase.closedCaseRevenue = (int) (0.75 * majorCasePrice);
}
casesVector.add(newCase);
}
try{
// Open a file to write to, named SavedCases.sav.
FileOutputStream saveFile = new FileOutputStream("SavedCases.sav", true);
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(casesVector);
save.close();
}
catch(Exception exc){
exc.printStackTrace();
}
Vector<Cases> comVector = new Vector<Cases>();
try{
FileInputStream saveFile = new FileInputStream("SavedCases.sav");
ObjectInputStream save = new ObjectInputStream(saveFile);
comVector = (Vector<Cases>) save.readObject();
System.out.println("The size of the vector is: " + comVector.size());
save.close(); // This also closes saveFile.
}
catch(Exception exc){
exc.printStackTrace();
}
for (Cases law_case : comVector) {
System.out.println("Name: " + law_case.caseName);
System.out.println("Client: " + law_case.client);
System.out.println("Case Type: " + law_case.caseType);
System.out.println("Case State: " + law_case.caseState);
System.out.println("Case Revenue: " + law_case.closedCaseRevenue);
System.out.println();
}
return casesVector;
}
EDIT: So to append to a vector if it already exists...
Check for an existing file using
File f = new File(FileName);
if(f.exists())
/* Read in the vector from the file using an object input stream on the file */
else
/* make a new vector */
Then read in your input and output it exactly as you have it there, however when you make the FileOutputStream do not include the true flag, this will cause you to add a new vector each time instead of just overwriting the current vector with the new, correct one.
ORIGINAL
The problem is with your implementation is that you are appending a new array each time you write to the save file. So whenever you try to read from the file, you are always getting that first array you ever made.
I am not sure whether you'd like to just overwrite the array with a new one each time, but you should either read in the current array before you add more cases or not set the append flag to true for the FileWriter constructor depending on your desired result.
Your code is running fine for me and is printing all the registered cases except that I am not appending to the already created file(that's what you want, right?). Couple of checks-
Is the class Cases implementing java.io.Serializable?
What is the visibility of the fields? default/private?
I see that you are not closing FileOutputStream and FileInputStream, is there a reason you are doing so?

Categories

Resources