Slower Java Asynchronous Client run after about one hour - java

I tried to connect with asynchronous socket and read new messages once per second.
I used sample client code (http://www.java2s.com/Tutorials/Java/Java_Network/0080__Java_Network_Asynchronous_Socket_Channels.htm) and in getTextFromUser method I added sleep method (with 1000 ms) and removed read command from user.
Additionally I added additional logic in ReadWriteHandler method. It started work great, but after about one hour program was suspended and has worked (execute my additional logic) not once per second but one per about 10 minutes.
Do you have any idea what might happen?
Part of code:
public void ConnectAsynchr() {
try {
this.channel = AsynchronousSocketChannel.open();
SocketAddress serverAddr = new InetSocketAddress("localhost", PortNumberAsynchr);
Future<Void> result = channel.connect(serverAddr);
try {
result.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.writeLog("ConnAsynch", "Asynchronous connection succesful established", true);
this.connectAsynch = true;
this.attach = new Attachment();
this.attach.channel = this.channel;
this.attach.buffer = ByteBuffer.allocate(16384);
this.attach.isRead = false;
this.attach.mainThread = Thread.currentThread();
ReadWriteHandler readWriteHandler = new ReadWriteHandler();
this.channel.write(this.attach.buffer, this.attach, readWriteHandler);
try {
this.attach.mainThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
this.writeLog("ERROR", e.toString(), false);
e.printStackTrace();
}
}
catch (IOException e) {
this.writeLog("ERROR", e.toString(), false);
System.out.println(e);
}
}
class Attachment {
AsynchronousSocketChannel channel;
ByteBuffer buffer;
Thread mainThread;
boolean isRead;
}
class ReadWriteHandler implements CompletionHandler<Integer, Attachment> {
#Override
public void completed(Integer result, Attachment attach) {
if (attach.isRead) {
attach.buffer.flip();
Charset cs = Charset.forName("UTF-8");
int limits = attach.buffer.limit();
byte bytes[] = new byte[limits];
attach.buffer.get(bytes, 0, limits);
String msg = new String(bytes, cs);
writeLog("Asynchr Msg rec", msg, false);
AsynchrMessLogic(msg);
try {
msg = this.getTextFromUser();
} catch (Exception e) {
e.printStackTrace();
}
if (msg.equalsIgnoreCase("bye")) {
attach.mainThread.interrupt();
return;
}
attach.buffer.clear();
byte[] data = msg.getBytes(cs);
attach.buffer.put(data);
attach.buffer.flip();
attach.isRead = false; // It is a write
attach.channel.write(attach.buffer, attach, this);
}else {
attach.isRead = true;
attach.buffer.clear();
attach.channel.read(attach.buffer, attach, this);
}
}
#Override
public void failed(Throwable e, Attachment attach) {
e.printStackTrace();
}
private String getTextFromUser() throws Exception{
/*System.out.print("\nPlease enter a message (Bye to quit):");
BufferedReader consoleReader = new BufferedReader(
new InputStreamReader(System.in));
String msg = consoleReader.readLine();
*/
Thread.sleep(threadSleep);
String msg="aaa";
return msg;
}
}

Related

Multithreaded UDP Server Java

I have two threads, one is listening on a socket and adding to the queue, the other subtracting from the queue and submitting for processing. The second thread has a sleep when the queue is empty. This sleep somehow affects the first thread, that is, if you remove sleep or make it larger, then the delay in socket.receive of the first thread increases. If I keep the sleep as low as possible, it gets better, but not perfect. What am I doing wrong?
private DatagramSocket socket;
private boolean running, listenthreadwork;
private byte[] buf = new byte[256];
private List<IUDPListener> listeners = new ArrayList<IUDPListener>();
private Thread runnerThread, listenerThread;
private ConcurrentLinkedQueue<MyObject> list = new ConcurrentLinkedQueue<MyObject>();
public void init(int port) throws SocketException
{
socket = new DatagramSocket(port);
runnerThread = new Thread(this::listenLoopUDP);
runnerThread.setName("listenLoopUDP");
listenerThread = new Thread(this::listenerThreadUDP);
listenerThread.setName("listenerThreadUDP");
running = true;
listenthreadwork = true;
runnerThread.start();
listenerThread.start();
}
private void listenerThreadUDP() {
while (listenthreadwork == true) {
MyObjectinfo = null;
synchronized (list) {
if (!list.isEmpty()) {
info = list.poll();
}
}
if (info != null) {
for (IUDPListener listener : listeners) {
listener.msgReceived(info);
}
} else {
try {
Thread.sleep(10);//Somehow affects listenLoopUDP
} catch (InterruptedException e) {
Log.write(e);
}
}
}
}
public void listenLoopUDP() {
while (running) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
socket.receive(packet);
} catch (IOException e) {
if (socket.isClosed()) {
running = false;
continue;
} else {
Log.write(e);
socket.close();
}
}
String received = new String(packet.getData());
MyObject info = new MyObject(received);
synchronized (list) {
list.offer(info);
}
}
listenthreadwork = false;
try {
listenerThread.join();
} catch (InterruptedException e) {
Log.write(e);
}
}
I have a simple client with timer
public class TestClient {
private DatagramSocket socket;
private InetAddress address;
private int count = 0;
public TestClient() {
try {
socket = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
address = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendEcho(String msg) {
msg = msg + count++;
ByteBuffer bb = ByteBuffer.allocate(256);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(msg.getBytes());
DatagramPacket packet = new DatagramPacket(bb.array(), bb.capacity(), address, 15000);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close() {
socket.close();
}
}
TestClient client = new TestClient();
Timer timer = new Timer(false);
timer.schedule(new TimerTask() {
#Override
public void run() {
client.send("hello");
}
}, 1, 1);
But in server I get message something like this
2021-05-17 20:04:48.320
2021-05-17 20:04:48.335
2021-05-17 20:04:48.351
2021-05-17 20:04:48.367
2021-05-17 20:04:48.382
It doesn't even help to remove it or not run listenerThread
synchronized (list) {
list.offer(info);
}
Actually you don't need to sleep, use proper queue classes instead, like LinkedBlockingQueue, I also remove the flags since you don't need them also, use interrupt() to stop a thread blocked waiting for a queue element:
private DatagramSocket socket;
private byte[] buf = new byte[256];
private List<IUDPListener> listeners = new ArrayList<IUDPListener>();
private Thread runnerThread, listenerThread;
private LinkedBlockingQueue<MyObject> list = new LinkedBlockingQueue<MyObject>();
public void init(int port) throws SocketException
{
socket = new DatagramSocket(port);
runnerThread = new Thread(this::listenLoopUDP);
runnerThread.setName("listenLoopUDP");
listenerThread = new Thread(this::listenerThreadUDP);
listenerThread.setName("listenerThreadUDP");
runnerThread.start();
listenerThread.start();
}
private void listenerThreadUDP() {
try {
while (true) {
MyObject info=list.take();
for (IUDPListener listener : listeners) {
listener.msgReceived(info);
}
}
} catch (InterruptedException ex) {
//Just quit
}
}
public void listenLoopUDP() {
try {
while (true) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData());
MyObject info = new MyObject(received);
list.put(info);
}
} catch (IOException e) {
Log.write(e);
} catch (InterruptedException e) {
Log.write(e);
} finally {
//Any exception above (or a runtime one) will activate this block where we do the cleanup and interrupt the other running thread
listenerThread.interrupt();
socket.close();
}
}
I did a test with your 1ms client, printing both sent and received message and I have a perfect interleaving between the message, so the bottleneck is not in the receiving thread; with perfect interleaving I mean that in the console I get, as expected, the sent message from the client immediately followed from the received message.

Notify client in client server application

first of all, I'm rather new to socket programming to go easy on me ;).
I have a Java program that uses client-server programming to communicate between 1 or more clients and the server. So the clients can send any number of messages to the server where the messages are dealt with and all is fine so far. Now I want to notify the clients of e.g. database changes on the server side. So for example if one client changes for example table A, the other clients should also be notified about this change.
What I have so far is the following (server):
ExecutorService executor = null;
try (ServerSocket socket = new ServerSocket(port);)
{
executor = Executors.newFixedThreadPool(getThreadCount(5));
while(true)
{
Socket clientSocket = socket.accept();
Runnable worker = new PCRequestMapper(clientSocket);
executor.execute(worker);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
finally
{
if(executor != null)
{
executor.shutdown();
}
}
The request mapper class then looks like this:
public class PCRequestMapper implements Runnable
{
private Socket client = null;
private static Map<Integer, PCRequestData> requestData = null;
public PCRequestMapper(Socket client)
{
this.client = client;
}
#Override
public void run()
{
try (ObjectInputStream in = new ObjectInputStream(
client.getInputStream());
ObjectOutputStream writer = new ObjectOutputStream(
client.getOutputStream());)
{
System.out.println("Thread started in PCRequestHandler with name: "
+ Thread.currentThread().getName());
Object recObj = in.readObject();
// ToDo Do something
PCBaseRequest req = (PCBaseRequest) recObj;
System.out.println("Req type: " + req.getRequestType() + " name: "
+ req.getName());
PCRequestData data = requestData.get(req.getRequestType());
if(data == null)
{
PCException ex = new PCException();
ex.setStackTrace(new Throwable().getStackTrace());
PCBaseReply reply = getErrorReply("No mapped request handler found in services.xml for request: "+req.getRequestType()+" - "+req.getName(),
PCException.NO_MAPPED_HANDLER, ex);
writer.writeObject(reply);
}
else
{
Class<?> c = Class.forName(data.getMappedClass());
Constructor<?> cons = c.getConstructor();
PCIRequestHandler object = (PCIRequestHandler)cons.newInstance();
PCBaseReply reply = object.heyHo(req);
System.out.println("Writing reply: "+reply.getClass());
writer.writeObject(reply);
}
} catch (IOException ioe)
{
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It basically takes a message (request), maps it to a configured class and then that class performs whatever action needed.
On the client side, I have a class called RequestSender, which is used to send arbitrary requests to the server:
public class PCRequestSender
{
private static int getPort(int defaultPort)
{
final String port = PCConfigHandler.getStringProperty("serverPort");
if (null != port)
{
try
{
return Integer.parseInt(port);
} catch (NumberFormatException e)
{
System.out.println("Value of port property"
+ " is not a valid positive integer [" + port + "]."
+ " Reverting to default [" + defaultPort + "].");
}
}
return defaultPort;
}
public static PCBaseReply sendRequest(PCBaseRequest req)
{
PCBaseReply reply = null;
int port = getPort(8081);
String address = PCConfigHandler.getStringProperty("serverAddress");
try (Socket serverSocket = new Socket(address, port);
ObjectOutputStream out = new ObjectOutputStream(
serverSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(
serverSocket.getInputStream());)
{
out.writeObject(req);
Object recObj = in.readObject();
reply = (PCBaseReply) recObj;
System.out.println("Reply: "+reply);
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return reply;
}
}
Now I'm a bit at a loss, because I would also like to constantly listen to a server socket to catch notifications. Do I need another socket on the server side? Is my setup not tooooo ideal?
I'm helpful for any hints...thanks!

Always get Broken pipe use sendUrgentData in my Socket Client

I wrote a SocketClient for connect to the socket, and add some callback in it.
public class SocketClientV2 {
public static void main(String[] args) {
SocketClientV2.Listener listener = new SocketClientV2.Listener() {
#Override
public void recv(byte[] result) {
// TODO Auto-generated method stub
System.out.println("====recv something");
}
#Override
public void connected() {
// TODO Auto-generated method stub
System.out.println("=====connected!");
}
#Override
public void disconnect() {
// TODO Auto-generated method stub
System.out.println("=====disconnect!");
}
};
SocketClientV2 client = new SocketClientV2("172.16.16.102", 4444,
10000, listener);
byte[] test = new byte[10];
test[0] = (byte) 0x1c;
test[1] = (byte) 0xff;
test[2] = (byte) 0x08;
client.send(test);
}
public interface Listener {
public void recv(byte[] result);
public void connected();
public void disconnect();
}
Socket client = null;
boolean isConnect = false;
OutputStream outputStream = null;
InputStream inputStream = null;
public SocketClientV2() {
}
Listener cb = null;
public SocketClientV2(String site, int port, int timeout, Listener cb) {
this.cb = cb;
try {
client = new Socket(site, port);
client.setSoTimeout(timeout);
System.out.println("Client is created! site:" + site + " port:"
+ port);
if (isConnected()) {
isConnect = true;
if (cb != null) {
cb.connected();
}
checkConnect();
listenRecv();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Socket getClient() {
return this.client;
}
public void closeSocket() {
try {
isConnect = false;
inputStream.close();
outputStream.close();
client.close();
client = null;
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean isConnected() {
try {
client.sendUrgentData(0xff);
isConnect = true;
} catch (Exception e) {
System.out.println("return false....2");
isConnect = false;
e.printStackTrace();
return false;
}
return true;
}
private void checkConnect() {
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("check connect....1");
try {
while (isConnected()) {
Thread.sleep(500);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("finally....3");
if (cb != null) {
cb.disconnect();
}
closeSocket();
}
}
}.start();
}
private void listenRecv() {
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("listening Recv....");
try {
inputStream = client.getInputStream();
while (isConnect) {
byte[] result = readStream(inputStream);
if (cb != null) {
cb.recv(result);
}
Thread.sleep(500);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
public void send(final byte[] byteSend) {
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
// System.out.println("sendMsg coming....");
if (isConnect) {
try {
outputStream = client.getOutputStream();
outputStream.write(byteSend);
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
public byte[] readStream(InputStream inStream) throws Exception {
int count = 0;
while (count == 0) {
// System.out.println(0);
count = inStream.available();
// if(count!=0)
// System.out.println(count);
}
byte[] b = new byte[count];
inStream.read(b);
return b;
}
}
there is one thread checkConnect to check the connect status for the socket..
but it will disconnect after running few mins,
Client is created! site:172.16.16.102 port:4444
=====connected!
check connect....1
listening Recv....
====recv something
====recv something
====recv something
====recv something
====recv something
====recv something
====recv something
return false....2
java.io.IOException: Broken pipe
at java.net.PlainSocketImpl.socketSendUrgentData(Native Method)
at java.net.PlainSocketImpl.sendUrgentData(PlainSocketImpl.java:622)
at java.net.Socket.sendUrgentData(Socket.java:954)
at com.udpdemo.multicast.SocketClientV2.isConnected(SocketClientV2.java:100)
at com.udpdemo.multicast.SocketClientV2.access$0(SocketClientV2.java:98)
finally....3
=====disconnect!
at com.udpdemo.multicast.SocketClientV2$2.run(SocketClientV2.java:121)
java.io.IOException: Stream closed.
at java.net.PlainSocketImpl.available(PlainSocketImpl.java:483)
at java.net.SocketInputStream.available(SocketInputStream.java:217)
at com.udpdemo.multicast.SocketClientV2.readStream(SocketClientV2.java:205)
at com.udpdemo.multicast.SocketClientV2$3.run(SocketClientV2.java:154)
so what's problem with my sendUrgentData???
'Broken pipe' always means that you wrote to a connection which had already been closed by the peer. It's an application protocol error.
But unless the peer of this client isn't written in Java there is no point in using urgent data in the first place. Java can only receive urgent data 'in-line', i.e. after all the other pending data that had already been sent. And that only happens if the peer calls setOOBLine(true), otherwise
by default, this option is disabled and TCP urgent data received on a socket is silently discarded.
It's possible you're doing this to detect a broken connection. In this case, your dream came true, it worked, and all you have to do is adjust your catch and your code accordingly. But this is not in general a reliable technique.
Other notes:
isConnected() can never be false at the point you test it after creating the Socket, and it never magically becomes false afterwards. You need to revisit all the code that calls this method. Most of it doesn't make sense, or relies on false assumptions.
Your readStream() method spin-loops while available() returns zero. There is absolutely no point in this. You're just smoking the CPU. It's also completely at odds with your attempted use of a read timeout, which simply cannot possibly work while this loop is there. The following read() call will block until at least one byte of data arrives, or end of stream or an exception occurs. Your present code will never detect end of stream. You need to completely redesign this part of the code as well. It's poor practice to return a byte array for example.
That same piece of code completely ignores the count returned by read(). Never do that.

java.io.StreamCorruptedException: invalid type code: 04

I have a little problem with my Client-Server Application. When I want to connect more than 1 Client and send smth, or I make logout in my Client and try to connect one more time I got Exception:
"java.io.StreamCorruptedException: invalid type code: 04"
What's the problem? Thank's for help.
Server Code:
class ClientCommunication implements Runnable {
private Socket incoming;
public ClientCommunication(Socket clientSocket) {
incoming = clientSocket;
}
public void run() {
try {
synchronized (this) {
serverObjectOutput = new ObjectOutputStream(
incoming.getOutputStream());
serverObjectInput = new ObjectInputStream(
incoming.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
int operation = -1;
synchronized(this) {
while (true) {
try{
if(serverObjectInput.available() > 0){
operation = serverObjectInput.readInt();
switch(operation) {
case 1:
Employee employee = (Employee) serverObjectInput.readObject();
//CHECK LOGGING DATA
// SEND RESULT = 1 OR RESULT = -1
break;
}
}
} catch(IOException | ClassNotFoundException | SQLException ex)
{
ex.printStackTrace();
}
}
}
}
}
class ServerStart implements Runnable {
private int portNumber;
public ServerStart(int portNumber) {
this.portNumber = portNumber;
}
public void run() {
try {
conn = getConnection();
stat = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
Socket incoming = serverSocket.accept();
Runnable r = new ClientCommunication(incoming);
Thread t = new Thread(r);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client Function:
public void actionPerformed(ActionEvent e) {
if (isConnected == false) {
String ServerIP = ip.getText().trim();
int ServerPort = Integer
.parseInt(port.getText().trim());
try {
ClientSocket = new Socket(ServerIP, ServerPort);
clientObjectInput = new ObjectInputStream(
ClientSocket.getInputStream());
clientObjectOutput = new ObjectOutputStream(
ClientSocket.getOutputStream());
isConnected = true;
} catch (IOException ex) {
ex.printStackTrace();
}
synchronized (this) {
try {
ClientLoginFrame login = new ClientLoginFrame();
Employee employee = login.getEmployee();
clientObjectOutput.writeInt(1);
clientObjectOutput.flush();
clientObjectOutput.writeObject(employee);
int result = clientObjectInput.readInt();
if(result == 1)
{
// DO SMTH
}
else {
isConnected = false;
ClientSocket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
I suspect your problem is that you are sharing the singletons serverInputStream and serverOutputStream between connections. This isn't a problem until you have more than one at which point using the same stream in multiple threads at once corrupts the stream (or makes reading it invalid)

Trouble Receiving image over socket

im tryin to send an image over socket , the sender part -(android)- looks short and ok, but the receiver part - which is written by java - is supposed to rename the image and save it in the C:/... . but i get nothing there and i cant find any problem with it ..
here is my server code:
public void start() throws InterruptedException {
keepGoing = true;
try
{
// the socket used by the server
ServerSocket serverSocket = new ServerSocket(port);
// infinite loop to wait for connections
while(keepGoing)
{
// format message saying we are waiting
display("Server waiting for Clients on port " + port + ".");
Socket socket = serverSocket.accept(); // accept connection
// if I was asked to stop
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket); // make a hread of it
jobdone=false;
al.add(t); // save it in the ArrayList
t.start();
}
// I was asked to stop
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
// not much I can do
}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
String msg = sdf.format(new Date()) +
" Exception on new ServerSocket: " + e +
"\n";
display(msg);
}
}
/*
* For the GUI to stop the server
*/
protected void stop() {
keepGoing = false;
// connect to myself as Client to exit statement
// Socket socket = serverSocket.accept();
try {
new Socket("192.168.1.2", 1500);
}
catch(Exception e) {
// nothing I can really do
}
}
/*
* Display an event (not a message) to the console or the GUI
*/
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else
sg.appendEvent(time + "\n");
}
// create a server object and start it
public static void shutdown() {
jobdone = true;
}
/** One instance of this thread will run for each client */
class ClientThread extends Thread {
// the socket where to listen/talk
String Type;
Socket socket;
InputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// Constructore
ClientThread(Socket socket) throws InterruptedException {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object I/O Streams");
// create output first
int bytesRead = 0;
int current = 0;
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
InputStream is = null;
try {
is = socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream("C:/IMG-20130112-WA0011.jpeg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // destination path and name of file
//FileOutputStream fos = new FileOutputStream("C:/");
BufferedOutputStream bos = new BufferedOutputStream(fos);
try {
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
current = bytesRead;
do {
try {
bytesRead =
is.read(mybytearray2, current, (mybytearray2.length-current));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
try {
bos.write(mybytearray2, 0 , current);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long end = System.currentTimeMillis();
//System.out.println(end-start);
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
am i doing any thing wrong guys ? thanks for reading in advance
The file path should be C:// instead of C:/

Categories