I'm having trouble getting my PrintStream to work correctly. I built a basic chatroom with commands (excuse my code if its messy, I just kind of threw it together) But the enter your name print statement only runs AFTER the name is inputted. So it hangs with a cursor until text is submitted then prints
Test (This is the input)
Enter your name:
Welcome to the channel Test. Current members: Test,
The first line is the input and the second and third is the resulting print statement. Is there a solution I'm missing? (All appropriate classes have been imported)
public class FinalProjectClientThread extends Thread
{
public DataInputStream is = null;
public PrintStream os = null;
public Socket clientSocket = null;
public final FinalProjectClientThread[] threads;
public int clientCount;
public String ClientName;
private boolean isModerator;
private boolean isMuted;
public FinalProjectClientThread(Socket clientSocket, FinalProjectClientThread[] threads)
{
this.clientSocket = clientSocket;
this.threads = threads;
clientCount = threads.length;
isModerator = false;
}
public String getClientName()
{
return ClientName;
}
private void setClientName(String n)
{
ClientName = n;
}
public void stopServer()
{
System.exit(0);
}
public void kickUser()
{
try
{
clientSocket.close();
}
catch(IOException e)
{
}
}
public void muteUser()
{
isMuted = true;
}
public void run()
{
int maxClients = this.clientCount;
FinalProjectClientThread[] threads = this.threads;
try
{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.flush();
os.print("");
os.flush();
os.print("Enter your name: ");
os.flush();
String name = is.readLine();
this.setClientName(name);
os.print("\nWelcome to the channel " + name+". ");
os.flush();
//Count number of users in channel
int count = 0;
for(int i = 0; i < maxClients; i++)
{
if(threads[i]!=null&&threads[i].getClientName() != null)
{
count++;
}
}
//Print text based on number
if(count == 0)
{
os.println("There are no other members.");
os.flush();
}
else
{
os.print("Current members: ");
os.flush();
}
//Print member's names
for(int i = 0; i < maxClients; i++)
{
if(threads[i]!=null&&threads[i].getClientName() != null)
{
os.print(threads[i].getClientName()+ ", ");
os.flush();
}
}
os.println();
os.flush();
for(int i = 0; i < maxClients; i++)
{
if (threads[i] != null && threads[i] != this)
{
threads[i].os.println(name + " has joined the channel");
}
}
while (true)
{
String line = is.readLine();
if (line.equals("/leave"))
{
break;
}
else if(line.equals("/mod"))
{
os.println("Enter the moderator code: ");
String line2 = is.readLine();
if(line2.equals("hurricanemod"))
{
isModerator = true;
for (int i = 0; i < maxClients; i++)
{
if (threads[i] != null)
{
threads[i].os.println(name+" is now a moderator");
}
}
}
else
{
os.println("That code is incorrect");
}
}
else if(line.equals("/help"))
{
os.print("The following commands are valid: leave, help, mod, kick, mute, unmute");
}
else if(line.indexOf("/kick") == 0)
{
if(isModerator)
{
for(int i = 0; i < maxClients; i++)
{
if(threads[i] != null && threads[i].getClientName().equals(line.substring(6, line.length())))
{
threads[i].kickUser();
}
}
os.println("User kicked");
}
else
{
os.println("You must be a moderator to kick people. Use /mod and the code provided by the server hoster");
}
}
else if(line.equals("/stop"))
{
if(isModerator)
{
this.stopServer();
}
else
{
os.println("You must be a moderator to stop the server. Use /mod and the code provided by the server hoster");
}
}
else if(line.indexOf("/mute") == 0)
{
if(isModerator)
{
for(int i = 0; i < maxClients; i++)
{
if(threads[i] != null && threads[i].getClientName().equals(line.substring(6, line.length())))
{
threads[i].muteUser();
}
}
os.println(line.substring(6, line.length())+ " was muted.");
}
else
{
os.println("You must be a moderator to kick people. Use /mod and the code provided by the server hoster");
}
}
else
{
if(!isMuted)
{
for (int i = 0; i < maxClients; i++)
{
if (threads[i] != null)
{
threads[i].os.println(name+": " + line);
}
}
}
else
{
os.println("You are muted");
}
}
}
for (int i = 0; i < maxClients; i++)
{
if (threads[i] != null && threads[i] != this)
{
threads[i].os.println(name + " left the channel");
}
}
os.println("You have left the channel");
for (int i = 0; i < maxClients; i++)
{
if (threads[i] == this)
{
threads[i] = null;
}
}
is.close();
os.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("IOExcepetion(Thread)");
}
}
}
Server
public class FinalProjectServer
{
private static Scanner kb = new Scanner (System.in);
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
private static int clientCount = 10;
private static FinalProjectClientThread[] clientList = new FinalProjectClientThread[clientCount];
public static void main(String[] args)
{
/*System.out.print("Enter port for server to run on: ");
int port = kb.nextInt();*/
int port = 25565;
try
{
serverSocket = new ServerSocket(port);
}
catch(IOException e)
{
System.err.println("IOException");
}
while(true)
{
try
{
clientSocket = serverSocket.accept();
int i = 0;
for(i = 0; i < clientCount; i++)
{
if(clientList[i] == null)
{
clientList[i] = new FinalProjectClientThread(clientSocket,clientList);
clientList[i].start();
break;
}
}
if(i == clientCount)
{
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Max number of client reached. Please contact server host.");
os.close();
clientSocket.close();
}
}
catch(IOException e)
{
System.err.println(e);
}
}
}
}
Client
public class FinalProjectClient implements Runnable
{
private static Scanner kb = new Scanner(System.in);
// The client socket
private static Socket clientSocket = null;
// The output stream
private static PrintStream os = null;
// The input stream
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args)
{
System.out.print("Enter the IP of the host computer: ");
String IP = kb.nextLine();
System.out.print("Enter the port number: ");
int port = kb.nextInt();
try
{
clientSocket = new Socket(IP, port);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
}
catch(UnknownHostException e)
{
System.err.println("Can not find host, Unknown");
}
catch(IOException e)
{
System.err.println("IOException");
}
try
{
new Thread(new FinalProjectClient()).start();
while(!closed)
{
os.println(inputLine.readLine());
}
os.close();
is.close();
clientSocket.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
public void run()
{
String reply;
try
{
while((reply = is.readLine()) != null)
{
System.out.println(reply);
if(reply.indexOf("/leave") != -1)
break;
}
closed = true;
}
catch(IOException e)
{
System.err.println(e);
}
}
}
Related
I'm trying to write a simple client/server application. I have a data on a client's side, that turns into an integer array and transfers to server. The server makes the calcutaions and returns them to client. But my program falls with this exception.
Sorry for long text, I'm just studying and really need your help.
public class Client {
private static Socket clientSocket;
private static ObjectInputStream in;
private static ObjectOutputStream out;
private static int[] parsedValue;
public Client(String input) {
try {
parsedValue = Arrays.stream(input.split(",")).mapToInt(Integer::parseInt).toArray();
} catch (Exception e) {
e.printStackTrace();
}
}
public Client(int[] input) {
parsedValue = input;
}
public Client(List<Integer> input) {
try {
parsedValue = input.stream().mapToInt(d->d).toArray();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
try {
clientSocket = new Socket("localhost", 4004);
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
String clientTestString = "440,5,16";
Client stringClient = new Client(clientTestString);
out.writeObject(stringClient.parsedValue);
out.flush();
System.out.println(in.readObject());
int[] clientIntsTest = {39, 10, 5};
Client arrayClient = new Client(clientIntsTest);
out.writeObject(arrayClient.parsedValue);
out.flush();
System.out.println(in.readObject());
List<Integer> clientsTestList = Arrays.asList(781, 9, 7);
Client listClient = new Client(clientsTestList);
out.writeObject(listClient.parsedValue);
out.flush();
System.out.println(in.readObject());
} finally {
System.out.println("Client was closed");
clientSocket.close();
in.close();
out.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
}
public class Server {
private static Socket clientSocket;
private static ServerSocket server;
private static ObjectInputStream in;
private static ObjectOutputStream out;
private static int[] parsedValue;
public String getResult() {
return calculation(parsedValue);
}
public String calculation(int[] parsedValue) {
parsedValue[0] = toDecimal(parsedValue[0], parsedValue[1]);
String answer = "";
int temp = 0;
String digits = new String("ABCDEF");
while (parsedValue[0] > 0) {
temp = parsedValue[0] % parsedValue[2];
if (temp < 10) {
answer = temp + answer;
} else {
answer = digits.charAt(temp - 10) + answer;
}
parsedValue[0] /= parsedValue[2];
}
return answer;
}
public int toDecimal(int value, int baseNotation) {
int i = 0;
int decimalNumber = 0;
if (value > 0) {
while (value != 0) {
decimalNumber += (value % 10) * Math.pow(baseNotation, i);
value /= 10;
i++;
}
}
return decimalNumber;
}
public static void main(String[] args) {
try {
try {
server = new ServerSocket(4004);
System.out.println("Server runs");
clientSocket = server.accept();
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
parsedValue = (int[]) in.readObject();
System.out.println(parsedValue);
Server examp = new Server();
String answer = examp.getResult();
System.out.println(answer);
out.writeObject(answer);
out.flush();
} finally {
clientSocket.close();
in.close();
out.close();
}
} finally {
System.out.println("Server closed");
server.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
}
In this two lines
Server examp = new Server();
String answer = examp.getResult();
you cretat a new object which overriddes the field private static ServerSocket server;
A better solution is to put the logic from your main() into a seperate method like run(), instantiate in main() a new object of server and call the run() on it. Dont't forget to make all fields as instance members by removing the static keyword.
public static void main(String[] args) {
Server examp = new Server();
examp.run();
}
public void run() {
try {
try {
server = new ServerSocket(4004);
System.out.println("Server runs");
clientSocket = server.accept();
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
parsedValue = (int[]) in.readObject();
System.out.println(parsedValue);
String answer = getResult();
System.out.println(answer);
out.writeObject(answer);
out.flush();
} finally {
clientSocket.close();
in.close();
out.close();
}
} finally {
System.out.println("Server closed");
server.close();
}
} catch (IOException | ClassNotFoundException e) {
System.err.println(e);
}
}
By the way: You should always use this patern to get out of the 'static-trap'. So I suggest you refactor your Client calss too.
I have kinda figured out how sockets work but I seem to have run into another wall. I'm supposed to somehow use the socket to transfer the data, but how? when I try it gives me a SocketException bind, saying it's already in use. I used it originally to connect it to a Directory, where I will gather other nodes and then if one doesn't have the data, it will ask for it from the other nodes.
class Download extends Thread {
CloudByte[] list = new CloudByte[1000000];
#Override
public void run() {
try {
var nodes = ConnectingDirectory.getNodes();
for (Nodes node : nodes) {
if ((node.getHostPort() == ConnectingDirectory.getHostIP())) {
downloadFile(node.getHostPort());
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
try {
fileWriting(getFile().getName(), list);
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void downloadFile(int port) throws IOException, ClassNotFoundException {
while (true) {
ServerSocket ss = ConnectingDirectory.getServerSocket();
Socket socket = ss.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
for (int j = 0; j <= 9999; j += 1) {
byte[] bit = (byte[]) ois.readObject();
for (int i = 0; i < bit.length; i++) {
list[i + j * 100] = new CloudByte(bit[i]);
}
}
System.out.println("Download Completed");
}
}
This is the function, I'm using to Download the date from the InputStream, the problem I'm having is that it's not downloading unless I restart the other Node. Is there a way to avoid having to do that? I really am at a loss.
Note; the for is because I need to transfer 1000000 bytes, in packets of 100 bytes.
The sending the data is:
class Upload extends Thread {
#Override
public void run() {
if (getFile().exists()) {
var nodes = ConnectingDirectory.getNodes();
for (Nodes node : nodes) {
if (node.getHostPort() == ConnectingDirectory.getHostIP()) {
try {
uploadFile(node.getHostPort());
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
new Download().start();
}
}
public static void uploadFile(int hostPort) throws IOException {
Socket socket = new Socket("localhost", hostPort);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ByteBlockRequest bbr = new ByteBlockRequest(getStoredData());
for (int j = 0; j <= 9999; j += 1) {
objectOutputStream.writeObject(bbr.blocksToSend(j));
}
objectOutputStream.flush();
System.out.println("Uploaded all the Data!");
}
Creating the server socket:
public ConnectingDirectory(String hostName, int hostIP, int directoryIP) throws IOException {
this.hostName = hostName;
this.directoryIP = directoryIP;
ConnectingDirectory.hostIP = hostIP;
this.address = InetAddress.getByName(hostName);
socket = new Socket(address, directoryIP);
serverSocket = new ServerSocket(hostIP);
signUp();
askConnectedNodes();
}
I'm working on a modbus UDP implementation [ J2Mod(2.3.4) ] in Java. I have found almost no useful documentation. I have a boolean array like flags.
Slave will read it via SimpleProcessImage->DigitalIn
Slave will use that flags and change them
Then write it to SimpleProcessImage->DigitalOut in every 10 secs.
I need help on 1st step. When I use master.readCoils(i, 1) and master.writeCoils(i, true). It only use DigitalOut. It write to DigitalOut and read from DigitalOut.
for (int i = 0; i < interSize ; i++) {
SimpleDigitalOut dout = (SimpleDigitalOut) image.getDigitalOut(i);
dout.set(i%5==0);
image.setDigitalOut(i, dout);
}
If I change DigitalOut on slave side as shown above, I can get changed values through DigitalOut. But I need to use them both; DigitalOut and DigitalIn.
Here's my code for slave.
public class Slave {
private SimpleProcessImage image;
private ModbusSlave slave;
private int interSize = 62000;
int step;
public Slave(){
image = new SimpleProcessImage();
step=0;
for (int i = 0; i < interSize; i++) {
image.addDigitalOut(i, new SimpleDigitalOut(false));
image.addDigitalIn(i, new SimpleDigitalIn(false));
}
(new Timer()).scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
read();
write();
}
}, 0, 10000);
startServer();
}
private void read() {
System.out.print("Read In : ");
for (int i = 0; i < interSize; i++) {
System.out.print((image.getDigitalIn(i).isSet() ? 1 : 0) + " ");
}
System.out.print("Read Out: ");
for (int i = 0; i < interSize; i++) {
System.out.print((image.getDigitalOut(i).isSet() ? 1 : 0) + " ");
}
}
public void startServer() {
try {
slave = ModbusSlaveFactory.createUDPSlave(502);
slave.addProcessImage(0, image);
slave.open();
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
Also here my client
public class Client {
private ModbusUDPMaster master;
int interSize = 62000 ;
Client() {
master = new ModbusUDPMaster("127.0.0.1", 502);
try {
master.connect();
} catch (Exception e) {
e.printStackTrace();
}
write();
while(true){
read();
}
}
public static void main(String... args) {
new Client();
}
private void write() {
for (int i = 0; i < interSize; i++) {
try {
master.writeCoil(i, i%3==0);
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
private void read() {
try {
for (int i = 0; i < interSize; i++) {
System.out.print(master.readCoils(i, 1).toString());
}
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
If anybody still looking for answer, as shown here, you can read DigitalIn via readInputDiscretes function.
Read Discretes
// master.readInputDiscretes(<discrete ref>, <count>); // Uses a UNIT ID of 1
master.readInputDiscretes(<unit id>, <discrete ref>, <count>);
I'm writing test for my chat-client system which works with sockets and 1 server. I have created 3 sockets(each one in thread representing client) which choose chat-room( "USA room") and all send 1 message, here is what I do-start the server, wait all clients to come in the room, each send a message, then read all messages from each socket,shutdown server, however while reading some socket's messages the test freezes. This freezing is caused by this line: String line = reader.readLine();. Some sockets receive the right amount of messages (which is 5), others just freeze with messages less than 5. I can't figure why the socket freeze.
public class ChatTest {
final int NUMBER_OF_SOCKETS = 3;
Server server = new Server();
Map<String, Socket> mapSockets = new ConcurrentSkipListMap<>();
List<String> socketMessages = new CopyOnWriteArrayList<>();
List<Thread> allThreads = new CopyOnWriteArrayList<>();
List<Socket> allsockets = new CopyOnWriteArrayList<>();
Set<Set<String>> allSets = new HashSet<>();
Map<Thread, Socket> mapThreadSocket = new ConcurrentHashMap<>();
private final CyclicBarrier barrier = new CyclicBarrier(NUMBER_OF_SOCKETS);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
server.start();
}
});
#BeforeSuite(alwaysRun = true)
public void startServer() {
t.start();
}
#AfterSuite(alwaysRun = true)
public void stopServer() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
server.stop();
}
Thread t2 = new Thread() {
#Override
public void run() {
try {
final List<String> linesFromFile = ChatSystemUtils.readFromFile(ClientTestDataConstants.TestDataFile.toString(), 50);
System.out.println("all client threads have entered room called USA room ");
for (int i = 0; i < NUMBER_OF_SOCKETS; i++) {
final PrintWriter stream = new PrintWriter(allsockets.get(i).getOutputStream(), true);
mapSockets.put(linesFromFile.get(i), allsockets.get(i));
stream.println(linesFromFile.get(i));
socketMessages.add(i, linesFromFile.get(i));
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < NUMBER_OF_SOCKETS; i++) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(allsockets.get(i).getInputStream()));
System.out.println("AT NEW USER");
Set<String> userMessages = new HashSet<>();
for (int j = 0; j < 5; j++) {
String line = reader.readLine();
System.out.println(line);
if (j > NUMBER_OF_SOCKETS) {
String msg = line.substring(9, line.length());
userMessages.add(msg);
}
}
userMessages.add(socketMessages.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
#Test
public void testMessagesReceived() throws IOException {
List<Thread> threadList = new LinkedList<>();
for (int i = 0; i < NUMBER_OF_SOCKETS; i++) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e1) {
e1.printStackTrace();
}
try {
Socket socket = new Socket("127.0.0.1", 3000);
allsockets.add(socket);
final PrintWriter stream = new PrintWriter(socket.getOutputStream(), true);
stream.println("USA room");
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread t = new Thread(r);
threadList.add(t);
}
for (int i = 0; i < threadList.size(); i++) {
threadList.get(i).start();
}
for (int i = 0; i < threadList.size(); i++) {
try {
threadList.get(i).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("most of the times we don't get here ");
}
}
Server class :
public final class Server {
public static boolean stopServerCalled;
private final int port;
private final String host;
private final Map<String, ChatRoom> mapRooms = ChatServerUtils.getChatRooms();
private final AtomicInteger clientID = new AtomicInteger(1);
private ServerSocket serverSocket;
private List<IClient> clientsPickingRoom;
private final ExecutorService executorService = Executors.newCachedThreadPool();
public Server() {
final Properties prop = new Properties();
try (final InputStream inputStream = getClass()
.getResourceAsStream("/com/egt/chat/server/ChatServerConfig.properties")) {// read from a file of
// properties
prop.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
this.port = Integer.parseInt(prop.getProperty("port"));
this.host = prop.getProperty("host");
this.clientsPickingRoom = new CopyOnWriteArrayList<>();
}
public void start() {
try {
final InetAddress address = InetAddress.getByName(host);
serverSocket = new ServerSocket(port, 50, address);
System.out.println("Listening on socket : " + serverSocket);
while (!Thread.currentThread().isInterrupted()) {
final Socket newSocket = serverSocket.accept();
System.out.println("Connection established with: " + newSocket);
final ClientContainer newClient = new ClientContainer(clientID.get(), newSocket);
executorService.execute(new ClientContainerRunnable(newClient, this));
clientID.incrementAndGet();
clientsPickingRoom.add(newClient);
}
} catch (IOException e) {
System.out.println("Server stopped!");
}
}
}
PrintWriter stream = new PrintWriter(allsockets.get(i).getOutputStream(), true);
stream.println(linesFromFile.get(i));
Isn't writing to this client socket, it's sending a message out to the server it's connected to. Where is the server writing the 5 lines to each client socket, which you read here:
for (int i = 0; i < NUMBER_OF_SOCKETS; i++) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(allsockets.get(i).getInputStream()));
for (int j = 0; j < 5; j++) {
String line = reader.readLine();
System.out.println(line);
// ...
It may be best if you dump all your code, then I could actually help. As it is, you aren't really helping me help you.
I can't work out what is causing this exception. It happens in the reRead() method.
I've tested it without reRead() method and everything else works fine.
public class SerFiles {
private ObjectInputStream in;
private ObjectOutputStream out;
private FileReader fr;
private FileWriter fw;
private BufferedReader br;
private BufferedWriter bw;
private StringTokenizer token;
private ArrayList<Product> prod = new ArrayList<Product>();
private String line = "c";
private Product proc;
private int a,b,d,e,f;
private String c;
public SerFiles(){ }
public void openFiles()
{
try
{
out = new ObjectOutputStream( new FileOutputStream( "prod.ser" ) );
fr = new FileReader("SalesDelim.txt");
br = new BufferedReader(fr);
System.out.println("OPEN SUCCESS");
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void readAndWrite()
{
try
{
line = br.readLine();
while(line != null)
{
if(line != null)
{
token = new StringTokenizer(line, "**");
a = Integer.parseInt(token.nextToken());
b = Integer.parseInt(token.nextToken());
c = token.nextToken();
d = Integer.parseInt(token.nextToken());
e = Integer.parseInt(token.nextToken());
f = Integer.parseInt(token.nextToken());
prod.add(new Product(a,c,e,f));
line = br.readLine();
}
}
for(int i = 0; i<prod.size(); i++)
{
out.writeObject(prod.get(i));
}
System.out.println("WRITE SUCCESS");
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void reRead()
{
try
{
in = new ObjectInputStream(new FileInputStream("prod.ser")); //////ERROR HAPPENS HERE
while(true)
{
proc = (Product)in.readObject();
System.out.println(proc.toString());
}
}
catch(EOFException ioe){
return;
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void closeFiles()
{
try
{
fr.close();
br.close();
out.close();
in.close();
System.out.println("CLOSE SUCCESS");
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
I've tested it without reRead() method and it worked fine.
Thank you
Try:
in = new ObjectInputStream(new FileInputStream("prod.ser"));
while (true)
{
proc = (Product)in.readObject();
System.out.println(proc); // change!!
if (proc == null) break; // quit the loop
}
So, the problem was that you were calling toString() on a null-pointer.