ObjectInputStream isn't finding any data to pull? - java

I am trying to read and write shape objects to a file for a drawing program, but when I try to read from the file it shows that the file is empty. The file is definitely being written to and updated, but when trying to read from the file it is showing that there are zero bytes available. The shape class is serializable so I am not sure why this isn't working at all.
public void writeToFile() {
try {
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\johnm\\eclipse-workspace\\CSE205_Assignment05\\save.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (Shape item : shapes) {
out.writeObject(item);
}
out.close();
fileOut.close();
System.out.println("Serialized data is saved in output.ser");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadFromFile() {
boolean cont = true;
Shape shape = null;
int count = 0;
while (cont) {
try {
FileInputStream fileIn = new FileInputStream("C:\\Users\\johnm\\eclipse-workspace\\CSE205_Assignment05\\save.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(in.available() + " Bytes");
if (in.available() != 0) {
shape = (Shape) in.readObject();
if (shape != null) {
shapes.add(shape);
count++;
} else {
System.out.println("Shape is null");
}
} else {
cont = false;
}
in.close();
fileIn.close();
System.out.println("Deserialized " + count + " Objects");
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Alright for some reason the .available() method isn't showing any bytes regardless of if there actually are any or not. To counter this I just threw in another try/catch statement where it continuously reads objects until it hits an EOFException and catches itself.
My code ended up looking like this once working.
public void loadFromFile() {
//** Loads set of shape objects from file
Shape shape = null;
int count = 0;
try {
FileInputStream fileIn = new FileInputStream("save.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(in.available() + " Bytes");
try {
while (true) {
shape = (Shape) in.readObject();
if (shape != null) {
shapes.add(shape);
count++;
} else {
System.out.println("Shape is null");
}
}
} catch (EOFException e) {
System.out.println("End of file exception");
}
in.close();
fileIn.close();
System.out.println("Deserialized " + count + " Objects");
repaint();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Java JSSC serial read consuming 100% CPU

I am trying to read GPS data from a serial port(ttyACM0) in java using jssc jar which I need to display as a label in a JavaFx application. I have a created a thread for reading the GPS data but this thread is consuming 100% CPU(checked using top command + Shift H) because of which my GUI is getting freezed. This is a sample code I have written for reading GPS data
Serial Interface
import jssc.*;
public class SerInterface {
String portName;
int baud;
boolean lineMode;
// The chosen Port itself
SerialPort port;
public byte[] recvBuff;
public SerInterface(String portName, int baud, boolean lineMode) {
this.portName = portName;
this.baud = baud;
this.lineMode = lineMode;
recvBuff = new byte[8192];
openPort();
if((port == null) || (!port.isOpened()))
System.out.println(portName + " not opened successfully");
}
void openPort() {
port = new SerialPort(portName);
if(port == null)
return;
try {
port.openPort();
} catch (SerialPortException e) {
e.printStackTrace();
}
try {
if(port.isOpened())
port.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
else
return;
} catch (SerialPortException e) {
e.printStackTrace();
}
System.out.println(portName + " opened successfully");
}
public int recvData() {
int len = 0;
if(port.isOpened()) {
try {
byte[] buff = port.readBytes();
if((buff == null) || (buff.length == 0))
return 0;
len = buff.length;
if(len > recvBuff.length)
len = recvBuff.length;
System.arraycopy(buff, 0, recvBuff, 0, len);
buff = null;
} catch (SerialPortException e) {
e.printStackTrace();
}
}
return len;
}
public void sendData(byte[] sendBuff, int len) {
if(port.isOpened()) {
try {
port.writeBytes(sendBuff);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
public boolean validatePort() {
if(!port.isOpened()) {
openPort();
if(port.isOpened())
return true;
else
return false;
}
else
return true;
}
public void flushPort() {
if(port.isOpened()) {
try {
port.purgePort(SerialPort.PURGE_RXCLEAR | SerialPort.PURGE_TXCLEAR);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
public void closePort() {
if(port.isOpened()) {
try {
port.closePort();
System.out.println("port closed");
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
}
GPSReceiver thread extends SerInterface and implements Runnable
#Override
public void run() {
flushPort();
while(true) {
if(!validatePort()) {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
int dataLength = recvData();
if(dataLength < 2)
continue;
try {
InputStream gpsStream = new ByteArrayInputStream(recvBuff, 0, dataLength);
BufferedReader br = new BufferedReader(new InputStreamReader(gpsStream, StandardCharsets.US_ASCII));
while(true) {
try {
if (!((output = br.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
extractData();
}
}
catch(NullPointerException e) {
e.printStackTrace();
}
}
Main Thread
GPSInterface objGPSThreadInterface = new GPSInterface(GPSPortName, 9600, true);
GPSThreadInt = new Thread(objGPSThreadInterface, "GPSINT");
I am using jdk-13.0.1 and jssc-2.9.1 jar

Sending an image through socket as byte array in Java

I know this has been asked in a few different ways, but I've been working on this for 2 days with no avail. My code is failing in that the receiving side throws EOF exceptions constantly. Can someone point me in the right direction?
Receiving side:
class ReceiveThread extends Thread {
ReceiveThread() {
}
#Override
public void run() {
System.out.println("Receive Thread Start");
DataInputStream in;
try {
} catch (Exception e) {
return;
}
try {
in = new DataInputStream(connection.getInputStream());
while (true) {
if (!connection.isConnected()) {
System.out.println("Connection not connected");
break;
}
try {
int len = in.readInt();
byte[] data = new byte[len];
System.out.println("Image size: " + len);
if (len > 0) {
in.readFully(data, 0, len);
BufferedImage bi = ImageIO.read(new ByteArrayInputStream(data));
panel.updateImage(bi);
panel.repaint();
}
in.close();
} catch (Exception e) {
}
pause(100);
}
} catch (Exception e) {
}
}
public void pause(long time) {
try {
Thread.sleep(time);
} catch (Exception e) {
}
}
}
Sending side:
class UpdateScreenThread extends Thread {
Robot robot;
public UpdateScreenThread() {
try {
robot = new Robot();
System.out.println("Update Thread Created");
} catch (Exception e) {
}
}
#Override
public void run() {
System.out.println("Update Thread Running");
Settings.isSharing = true;
Dimension screenSize;
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out;
try {
out = new DataOutputStream(s.getOutputStream());
} catch (Exception e) {
return;
}
while (s.isConnected()) {
//System.out.println("test");
BufferedImage bi = robot.createScreenCapture(screenRectangle);
try {
ImageIO.write(bi, "PNG", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
out.flush();
out.writeInt(bytes.length);
out.flush();
out.write(bytes);
System.out.println("Image sent");
} catch (Exception e) {
}
pause(500);
}
try {
out.close();
} catch (Exception e) {
}
Settings.isSharing = false;
}
}
Thanks to anyone who can help. This is driving me INSANE.
Reduced to the essentials, this is your read loop:
public void run() {
//...
try {
in = new DataInputStream(connection.getInputStream());
while (true) {
//...
try {
int len = in.readInt();
byte[] data = new byte[len];
in.readFully(data, 0, len);
//...
in.close();
} catch (Exception e) {
}
pause(100);
}
} catch (Exception e) {
}
}
Note that the while (true) {...} includes in.close(). Move the close out of the loop.

AudioRecord not saving

I am trying to record the audio using AudioRecorde.
Though it creates file but could not record it. Please provide some inputs.
private void startRecording(){
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,44100,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT));
try {
recorder.startRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
At the time of stoprecording
private void stopRecording(){
if(null != recorder){
recorder.stop();
recorder.release();
FileOutputStream fOut = null;
try{
int buffSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
//ByteBuffer buffer = ByteBuffer.allocate(AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT));
byte b[] = new byte[buffSize];
recorder.read(b,0,buffSize);
//getFilename() will get the file
fOut = new FileOutputStream(getFilename());
fOut.write(b);
}catch(Exception e){
e.printStackTrace();
}finally{
if(fOut != null){
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
recorder = null;
}
}
It creates a file with buffsize but could not play it.
Here is the code for playing the file
private void startPlaying() {
mPlayer = new MediaPlayer();
if(playing){
playing = false;
}else{
try {
File myFile = new File(prevFile);
txtStatus.setText("Playing...");
imgStatus.setVisibility(View.VISIBLE);
imgStatus.setBackgroundDrawable(getResources().getDrawable(R.drawable.play_small));
if(myFile.exists()){
System.out.println("file is exist");
}else{
System.out.println("file is not exist");
}
mPlayer.setDataSource(prevFile);
System.out.println("file path is is ::> " + prevFile);
mPlayer.prepare();
mPlayer.start();
playing = true;
} catch (IOException e) {
e.printStackTrace();
write.saveToFile(getApplicationContext(), "prepare() failed"+"\n");
}
}
}

Sending image Through TCP Socket in Java

I'm trying to make a Client Server Application which the server list name of available images and the client select one of them to download Such as here :
Thread in Server
public void run()
{
try {
in = new DataInputStream (server.getInputStream());
out = new DataOutputStream(server.getOutputStream());
out.writeUTF("To List images write list");
out.writeUTF("To Exit write 2");
out.flush();
while((line = in.readUTF()) != null && !line.equals("2")) {
if(line.equalsIgnoreCase("list"))
{
String [] images= processor.listImages();
for ( int i=0;i<images.length;i++) {
out.writeUTF((+1)+"-"+images[i]);
out.flush();
line = "";
}
out.writeUTF("-1");
line = in.readUTF();
if(line.equalsIgnoreCase("2"))
{
break;
}else
{
BufferedImage img =processor.processInput(line);
boolean cc = ImageIO.write(img,"JPG",server.getOutputStream());
if(!cc)
{
out.writeUTF("The entered image is not avaliable !");
}else
{
System.out.println("Image Sent");
}
}
}else if(line.equalsIgnoreCase("2")){
break;
}
}
try{
in.close();
out.close();
server.close();
}catch(Exception e){
System.out.println("Error : "+ e.getMessage());
}
} catch (IOException e) {
System.out.println("IOException on socket listen: " + e.getMessage());
}
}
Client :
public void start() throws IOException
{
String line="";
while(true)
{
try{
line = inputFromStream.readUTF();
System.out.println(line);
line = inputFromStream.readUTF();
System.out.println(line);
line = readFromConsol.readLine();
writeToStream.writeUTF(line);
if(line.equalsIgnoreCase("2")){
break;
}else if(line.equalsIgnoreCase("list")){
boolean check=true;
while(check){
line = inputFromStream.readUTF();
System.out.println(line);
if("-1".equals(line)) {
check=false;
}
}
line = readFromConsol.readLine();
if(line.equalsIgnoreCase("2")) {
break;
}else
{
writeToStream.writeUTF(line);
BufferedImage img=ImageIO.read(
ImageIO.createImageInputStream(client.getInputStream()));
File f = new File("E:/MyFile.png");
f.createNewFile();
ImageIO.write(img, "PNG", f);
//process.saveImage(tmp);
System.out.println("Saved");
}
}
}catch(Exception e)
{
System.out.println(e);
break;
}
}
try{
inputFromStream.close();
readFromConsol.close();
writeToStream.close();
this.client.close();
}catch(Exception e){
System.out.println("Error : "+e.getMessage());
}
}
The problem is that all commands are successfully submitted till image receiving image stop there doesn't move
Try doing a flush of the outstream on the sending socket, then close the socket.
The problem appears to be that until the socket is flushed and closed the receiving IOImage.read() will wait thinking there are more images in the stream.

Issue writing to serial port from Java [duplicate]

This question already has answers here:
Closed 13 years ago.
Duplicate of Implementation of Xmodem Protocol in Java
I've got to implement the xmodem protocol to receive a file from a target device. For that, I have to request the file, then for every 128-byte packet received, I have to send an acknowledgment. My problem is when I open an outputstream to request the file, it will write but after that I can't write again to the outputstream. What is the problem I'm not getting?
package writeToPort;
import java.awt.Toolkit;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.JOptionPane;
import constants.Constants;
public class Flashwriter implements Runnable, SerialPortEventListener {
Enumeration portList;
CommPortIdentifier portId;
String messageString = "\r\nFLASH\r\n";
SerialPort serialPort;
OutputStream outputStream,outputStream2;
InputStream inputStream;
//Thread readThread;
String one, two;
String test = "ONLINE";
String[] dispArray = new String[1];
int i = 0;
Thread readThread;
byte[] readBufferArray;
int numBytes;
String response;
FileOutputStream out;
final int FLASH = 1, FILENAME = 2;
int number;
File winFile;
public static void main(String[] args) throws IOException {
Flashwriter sm = new Flashwriter();
sm.FlashWriteMethod();
}
public void FlashWriteMethod() throws IOException {
portList = CommPortIdentifier.getPortIdentifiers();
winFile = new File("D:\\testing\\out.FLS");
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM2")) {
// if (portId.getName().equals("/dev/term/a")) {
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp",
1000);
} catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
System.out.println(" Input Stream... " + inputStream);
} catch (IOException e) {
System.out.println("IO Exception");
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Tooo many Listener exception");
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort
.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// serialPort.disableReceiveTimeout();
// outputStream.write(messageString.getBytes());
// sendRequest("/r/n26-02-08.FLS/r/n");
number = FLASH;
sendRequest(number);
} catch (UnsupportedCommOperationException e) {
}
}
}
}
}
public void serialEvent(SerialPortEvent event) {
SerialPort port = (SerialPort) event.getSource();
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
try {
while (inputStream.available() > 0) {
numBytes = inputStream.available();
readBufferArray = new byte[numBytes];
// int readtheBytes = (int) inputStream.skip(2);
int readBytes = inputStream.read(readBufferArray);
one = new String(readBufferArray);
System.out.println("readBytes " + one);
if (one.indexOf("FLASH_") > -1 & !(one.indexOf("FLASH_F") > -1)) {
System.out.println("got message");
response = "FLASH_OK";
// JOptionPane.showMessageDialog(null,
// "ONLINE",
// "Online Dump",
// JOptionPane.INFORMATION_MESSAGE);
// Toolkit.getDefaultToolkit().beep();
// outputStream.write("\r\nONLINEr\n".getBytes());
// outputStream.flush();
// outputStream.write("/r/n26-02-08.FLS/r/n".getBytes());
number = FILENAME;
sendRequest(number);
}
out = new FileOutputStream(winFile, true);
out.write(readBufferArray);
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
readBufferArray = null;
// break;
}
// try {
// int c;
// while((c = inputStream.read()) != -1) {
// out.write(c);
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// // readBufferArray=null;
// break;
// }
// if (inputStream != null)
// try {
// inputStream.close();
// if (port != null) port.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
//
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
System.out.println("In run() function ");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted Exception in run() method");
}
}
public void dispPacket(String packet) {
if (response == "FLASH_OK") {
System.out.println("disppacket " + packet);
} else {
System.out.println("No resust");
}
}
public void sendRequest(int num) {
switch (num) {
case FLASH:
try {
// outputStream = serialPort.getOutputStream();
outputStream.write("AT".getBytes());
// outputStream.write("\r\n26-02-08.FLS\r\n".getBytes());
System.out.println("Flash switch");
// outputStream.close();
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
case FILENAME:
try {
//outputStream =(serialPort.getOutputStream());
outputStream.write("\r\nSUNSHINE\\06-03-09.FLS\r\n".getBytes());
System.out.println("File name");
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Perhaps the streams are blocking.
Java nio has channels that do not block. Try using one of those.
Here's a sample of reading a file with nio. I'm not sure if the same applies for you or not.
I hope it helps.

Categories