This question already has answers here:
Java FileInputStream ObjectInputStream reaches end of file EOF
(9 answers)
Closed 8 years ago.
Please have a look at below code
public class xina {
static name[] Name;
public static void main(String[] args) throws Exception {
Name = new name[3];
Name[0] = new name("Hugh", "Jackman");
Name[1] = new name("John", "TRavolta");
Name[2] = new name("Megh", "Ryne");
File ff = new File("object.txt");
FileOutputStream fo = new FileOutputStream(ff.getName());
ObjectOutputStream oo = new ObjectOutputStream(fo);
for (name dd : Name) {
System.out.println(dd.getfistName() + " " + dd.getlastName());
oo.writeObject(dd);
}
oo.close();
FileInputStream fi = new FileInputStream(ff.getName());
ObjectInputStream oi = new ObjectInputStream(fi);
name hh;
try {
while ((hh = (name) oi.readObject()) != null) {
System.out.println(hh.fistName);
}
} catch (EOFException e) {
System.out.println("file ended");
}
}
}
here "name" is class which save first name and last name.
How can i read the file without using exception.
My point is it is trying to read when no more objects exists look like null check is not sufficing the need.
THanks in advance.
while ((hh = (name) oi.readObject()) != null) {
The problem is here. readObject() returns null if you wrote a null, and not otherwise. The correct test for reading past end of stream is to catch EOFException.
Problem here is that the method InputStream#readObject does not return null object past EOF it always throws an Exception. The Simple solution to that is while serializing pass the size of the array first and read the size first and then the array of that size while de-serializing.
So while writing:
oo.writeObject(new Integer(Name.length));
for (name dd : Name) {
System.out.println(dd.getfistName() + " " + dd.getlastName());
oo.writeObject(dd);
}
while reading:
ObjectInputStream oi = new ObjectInputStream(fi);
Integer size = oi.readObject();
name hh;
for (int i=0;i<size;i++) {
hh= (Name) oi.readObject();
System.out.println(hh.fistName);
}
Hope this helps.
Related
This question already has answers here:
Java: How to read a text file
(9 answers)
Closed 3 years ago.
I have a problem because I don't know how to read a line from a file (I searched, I tried and nothing worked). I need it because I want to use it in my future project (list of blocked players on the server in my game). At the beginning, I save the player and the reason for the ban to the HashMap. Then I have to read this nickname and separate it from the reason and check if the nickname (parameter in the checkPlayerOnTheBanList method (String nick)) agrees with the name in the file to which I saved HashMap. Then if the name (parameter) matches with the name in the file then the player won't be able to enter to the server. Here is the content of the bannedplayers.txt file:
hacker=Cheating!
player=Swearing!
Here is the part of Server.java:
public HashMap<String, String> bannedPlayersWr = new HashMap<String, String>();
public void start(String nick) {
banPlayer("player", "Swearing!");
banPlayer("hacker", "Cheating!");
boolean player = checkPlayerOnBanMap(nick);
if (player) {
System.out.println("You are banned! Your nick: " + nick);
System.out.println("Reason: " + bannedPlayersWr.get(nick));
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter("C:/Users/User/Desktop/bannedplayers.txt");
out = new BufferedWriter(fstream);
Iterator<Entry<String, String>> it = bannedPlayersWr.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> pairs = it.next();
out.write(pairs.toString() + "\n");
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Welcome to the server! Your nick: " + nick);
}
}
private void banPlayer(String nick, String reason) {
bannedPlayersWr.put(nick, reason);
}
A simple way to read a file line by line and put each line as an element in a list, hope it helps you to modify it to your need.
private List<String> readFile(String filename)
throws Exception
{
String line = null;
List<String> records = new ArrayList<String>();
// wrap a BufferedReader around FileReader
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
// use the readLine method of the BufferedReader to read one line at a time.
// the readLine method returns null when there is nothing else to read.
while ((line = bufferedReader.readLine()) != null)
{
records.add(line);
}
// close the BufferedReader when we're done
bufferedReader.close();
return records;
}
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;
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So I'm trying to take a series of "scores" from a text file to put into an array and then sort in order, rows of four, and write other methods to get the highest, lowest, average, etc. The println commands are in there but I haven't written the methods yet. I've been working all day and I'm starting to confuse myself, and now I'm getting a NullPointerException error in the main method. Any help?
package arrayops1d;
import java.io.*;
import java.util.*;
public class ArrayOps1D {
static int scores[];
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
BufferedReader reader = new BufferedReader(file);
String scores = "";
String line = reader.readLine();
while (line != null){
scores += line;
line = reader.readLine();
}
System.out.println(scores);
System.out.println(getTotal());
System.out.println(getAverage());
System.out.println(getHighest());
System.out.println(getLowest());
System.out.println(getMedian());
System.out.println(getPosition());
System.out.println(getDeviations);
System.out.println(getStdDev);
}
Here is one way you can read the int values from a file into an array of Integer using a Scanner and a List -
Integer[] scores = null;
File file = new File("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
if (file.exists() && file.canRead()) {
try {
List<Integer> al = new ArrayList<>();
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
al.add(scanner.nextInt());
} else {
System.out.println("Not an int: " + scanner.next());
}
}
scores = al.toArray(new Integer[al.size()]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("Can't find file: " + file.getPath());
}
if (scores != null) {
System.out.println("Scores Read: " + Arrays.toString(scores));
}
First Issue with your code:
In your file path, Instead using / , you must use \\ or better File.separator if your program wants to be ran in different platform.
If you do not , you will have java.io.FileNotFoundException
You are reading line by line, so you can use split Function and use Integer.paraseInt or Float.parseFloat to convert each splited elements and added to your array
How to use Split in Java
How to convert String to int
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
I currently have an array that holds a set of commands issued from a GUI. I can print out the list of commands to the screen, but am having trouble writing those commands to a text file. I need some advice. This is the code that prints to the console.
for (int i = 0; i < movementArray.length; i++)
{
System.out.println(movementArray[i]);
}
First use a StringBuilder to create your String:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < movementArray.length; i++)
{
sb.append(movementArray[i]);
}
setContents(new File("your path here"), sb.toString());
The setContents(File aFile, String aContents) method will set a string content in a file.
public static void setContents(File aFile, String aContents)
throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
//declared here only to make visible to finally clause; generic reference
Writer output = null;
try {
//use buffering
//FileWriter always assumes default encoding is OK!
output = new BufferedWriter(new FileWriter(aFile));
output.write(aContents);
} finally {
//flush and close both "output" and its underlying FileWriter
if (output != null) {
output.close();
}
}
}
Use PrintWriter or BufferedWriter.
http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1 answer)
Closed 5 years ago.
I am dumping an arraylist of object into a file.I am serialising object by object and logging into a file instead of whole arraylist serialisation because no. of arraylist can be mor than one. The process is working fine and data is appending in the file but during the deserialisation i can retrieve only first arraylist objects and as soon as second arraylist objects come it throws java.io.StreamCorruptedException: invalid type code: AC . My each arraylist have same type of objects. I have tried to search a lot but none of the tricks like reset, AppendableObjectoutputstream are working.
My serialising code is:
public static void dumplogInFile(ArrayList<HtmlElementObject> sanitizelog)
{
try
{
String fileName = "c:\\temp\\ auditinfo.ser";
FileOutputStream fileOut =
new FileOutputStream(fileName , true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for(HtmlElementObject eachobj : sanitizelog)
{
out.writeObject(eachobj);
out.reset() ;
}
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/auditinfo.ser");
//logElementData.clear();
}catch(IOException i)
{
i.printStackTrace();
}
}
here number of arraylist will be more instead of one as it works like that if webservice will fail then it will dump the data in file.
My Deserialising Code to read data from file
public static ArrayList<HtmlElementObject> extractLogFromFile()
{
HtmlElementObject v ;
ArrayList<HtmlElementObject> extractLogList = new ArrayList<HtmlElementObject>();
try
{
FileInputStream fileIn = new FileInputStream("c:\\temp\\ auditinfo.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
// ObjectInputStream in = new ObjectInputStream(fileIn);
/* ArrayList<HtmlElementObject> arr = (ArrayList<HtmlElementObject>) in.readObject();
// for (HtmlElementObject a : arr)
// {
//a = (HtmlElementObject) in.readObject();
//extractLogList.add(a);
//}*/
int count =0;
while( (v = (HtmlElementObject)in.readObject()) != null)
{
System.out.println(count++);
HtmlElementObject a;
a = v;//(HtmlElementObject) in.readObject();
extractLogList.add(a);
}
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return extractLogList ;
}catch(ClassNotFoundException c)
{
System.out.println(" class not found");
c.printStackTrace();
return null ;
}
return extractLogList;
}
}
Now this function will easily read all the objects of first arraylist but as the new arraylist object will come then it throws java.io.StreamCorruptedException.
You can't append to object stream files without a special trick to suppress the second stream header which is written by the constructor of ObjectOutputStream. Your ObjectInputStream is encountering that where it expects an object, and barfing.