Open file after transfer - java

i would like to know if it was possible in to do this in java. This is my code :
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 13267; // you may change this
public final static String SERVER = "192.168.0.36"; // localhost
public final static String
FILE_TO_RECEIVED = "c:/temps/source-downloaded.mp3"; // you may change this, I give a
// different name because i don't want to
// overwrite the one used by server...
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
And i would like to know if it was possible for the file to open AFTER the transfer has been done. Thank you for your answers.

Related

Java server invalid execption. Socket

I have been fixing my server many times and now i'm stuck ones again.
So I have been trying to send pictures through my clientGUI to a server, So the person can see the file im sending. I dont really know how to explain this. but however. Im just trying to send a file so the other client can accept it and save it. BUT as fast as I press the button picture (It should automatic send a picture to a desktop that I have placed) it does work,
Connection is accepted; localhost/127.0.0.1 - 1500
Sending C:/Users/Barry/Desktop/Ceo/Cao6.jpg(15306 bytes)
Server has closed the connection
but i'm not getting anything in the desktop and in my ServerGUI, I can see that it says :
Exception reading Streams: java.io.StreamCorruptedException: invalid type code: FF
which I have no idea how to fix it and I need some ideas how I can fix this.
Sendpic.java
public void SendPic() throws IOException {
JFileChooser chooser = new JFileChooser();
String FILESEND = "C:/Users/Barry/Desktop/Ceo/Cao6.jpg";
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
// send file
File myFile = new File (FILESEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = socket.getOutputStream();
System.out.println("Sending " + FILESEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
} catch (IOException e) {
e.printStackTrace();
}
}
getPic.Java
final static int FILE_SIZE = 6022386;
public void getPic() throws IOException {
JFileChooser chooser = new JFileChooser();
String FILETORECEIVED = "C:/Users/Barry/Desktop/";
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = socket.getInputStream();
fos = new FileOutputStream(FILETORECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_SIZE
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
}
}
ActionPerformed`
public void actionPerformed(ActionEvent e) {
Object button = e.getSource();
if (button == btnPicture) {
try {
controller.SendPic();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return;
}`

client program read the file very slow in java

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
public class Client {
public static void main (String [] args ) throws IOException {
int filesize=2022386;
int bytesRead;
int currentTot = 0;
Socket socket = new Socket("192.168.1.6",15123);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("d:\\copy.rar");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do {
bytesRead =
is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead;
} while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}
In above is my client code it reads the data from server in very slow manner can you suggest me to increase the transfer speed.can i read video files using this code if not suggest idea to do that.

Java threaded TCP server sockets [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have an android client and a multithreaded Java server. The server was originally written in Python and worked great, but now that I re-wrote it in Java it doesn't seem to be working. Below is my server code. It may be worth noting that the Python implementation was not multithreaded, but I don't think I would need to change the client for that anyway.
import java.net.*;
import java.io.*;
import org.apache.commons.io.FileUtils;
public class MultiServerThread extends Thread {
private Socket socket = null;
public MultiServerThread(Socket socket) {
super("MultiServerThread");
this.socket = socket;
}
#Override
public void run() {
try {
String path = "C:/Users/LandClan/Desktop/cubikal";
int count = 0;
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
DataInputStream dis = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
File[] files = new File(path).listFiles();
for (File file : files) {
String filename = file.getName();
String extension = filename.substring(
filename.lastIndexOf(".") + 1, filename.length());
if ("png".equals(extension)) {
count += 1;
}
}
System.out.println("Sending " + count + " files");
dos.writeInt(count);
byte[] temp = new byte[1024];
int n = 0;
for (File file : files) {
String filename = file.getName();
String extension = filename.substring(
filename.lastIndexOf(".") + 1, filename.length());
if ("png".equals(extension)) {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte fileContent[] = new byte[(int) file.length()];
bis.read(fileContent);
int dataLength = fileContent.length;
dos.writeInt(dataLength);
System.out.println(filename + " is " + dataLength
+ " bytes long");
while ((dataLength > 0)
&& (n = bis.read(temp, 0,
(int) Math.min(temp.length, dataLength))) != -1) {
dos.write(temp, 0, n);
dos.flush();
dataLength -= n;
}
// System.out.println("Sent file "+filename);
fis.close();
}
}
for (File file1 : files) {
String filename = file1.getName();
String extension = filename.substring(
filename.lastIndexOf(".") + 1, filename.length());
if ("txt".equals(extension)) {
FileInputStream fis = new FileInputStream(file1);
BufferedInputStream bis = new BufferedInputStream(fis);
byte fileContent[] = new byte[(int) file1.length()];
bis.read(fileContent);
int dataLength = fileContent.length;
dos.writeInt(dataLength);
System.out.println("file is " + dataLength + "long");
while ((dataLength > 0)
&& (n = bis.read(temp, 0,
(int) Math.min(temp.length, dataLength))) != -1) {
dos.write(temp, 0, n);
dos.flush();
dataLength -= n;
}
// System.out.println("Sent file");
fis.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
here is the first part of the server
package server;
import java.net.*;
import java.io.*;
public class Server {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4447);
} catch (IOException e) {
System.err.println("Could not liten on port: 4447.");
System.exit(-1);
}
while (listening) {
new MultiServerThread(serverSocket.accept()).start();
}
serverSocket.close();
}
}
The DataOutputStream never seems to get closed, and the DataInputStream is never used at all.
Get rid of the DataInputStream , and make sure you close the DataOutputStream when you have finished with it.
A good way is to add a finally{} block to your try-catch, although you'll need to declare the DataOutputStream outside of the try-catch so it is visible in the finally.
DataOutputStream dos = null;
try
{
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
// do stuff
}
catch(IOException e)
{
//stacktrace etc
}
finally
{
if (dos != null) dos.close();
}
This kind of stuff is always a bit ugly in Java, though upcoming versions may make it better...

Java sending and receiving file (byte[]) over sockets

I am trying to develop a very simple client / server where the client converts a file to bytes, sends it to the server, and then converts the bytes back in to a file.
Currently the program just creates an empty file. I'm not a fantastic Java developer so any help much appreciated.
This is the server part that receives what the client sends.
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(4444);
Socket socket = null;
socket = serverSocket.accept();
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte[] bytes = new byte[1024];
in.read(bytes);
System.out.println(bytes);
FileOutputStream fos = new FileOutputStream("C:\\test2.xml");
fos.write(bytes);
And here is the client part
Socket socket = null;
DataOutputStream out = null;
DataInputStream in = null;
String host = "127.0.0.1";
socket = new Socket(host, 4444);
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
File file = new File("C:\\test.xml");
//InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
//out.write(bytes);
System.out.println(bytes);
out.close();
in.close();
socket.close();
The correct way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Wish I had a dollar for every time I've posted that in a forum.
Thanks for the help. I've managed to get it working now so thought I would post so that the others can use to help them.
Server:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
out = new FileOutputStream("M:\\test2.xml");
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[16*1024];
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
serverSocket.close();
}
}
and the Client:
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 4444);
File file = new File("M:\\test.xml");
// Get the size of the file
long length = file.length();
byte[] bytes = new byte[16 * 1024];
InputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
}
}
Here is the server
Open a stream to the file and send it overnetwork
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleFileServer {
public final static int SOCKET_PORT = 5501;
public final static String FILE_TO_SEND = "file.txt";
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
} catch (IOException ex) {
System.out.println(ex.getMessage()+": An Inbound Connection Was Not Resolved");
}
}finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null)
servsock.close();
}
}
}
Here is the client
Recive the file being sent overnetwork
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 5501;
public final static String SERVER = "127.0.0.1";
public final static String
FILE_TO_RECEIVED = "file-rec.txt";
public final static int FILE_SIZE = Integer.MAX_VALUE;
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];, instead we could do
byte[] bytearray = new byte[1024*16];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
OutputStream output= socket.getOututStream();
BufferedInputStream bis = new BufferedInputStream(fis);
int readLength = -1;
while ((readLength = bis.read(bytearray)) > 0) {
output.write(bytearray, 0, readLength);
}
bis.close();
output.close();
}
catch(Exception ex ){
ex.printStackTrace();
} //Excuse the poor exception handling...
Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html
Adding up on EJP's answer; use this for more fluidity.
Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:
int count;
byte[] bytes = new byte[4096];
try {
while ((count = is.read(bytes)) > 0) {
System.out.println(count);
bos.write(bytes, 0, count);
}
} catch ( Exception e )
{
//It will land here....
}
// Then continue from here
EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!
Hope this post solves any of your issues

How do you uncompress a split volume zip in Java?

I need to reassemble a 100-part zip file and extract the content. I tried simply concatenating the zip volumes together in an input stream but that does not work. Any suggestions would be appreciated.
Thanks.
Here is the code you can start from. It extracts a single file entry from the multivolume zip archive:
package org.test.zip;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] args) throws IOException {
ZipInputStream is = new ZipInputStream(new SequenceInputStream(Collections.enumeration(
Arrays.asList(new FileInputStream("test.zip.001"), new FileInputStream("test.zip.002"), new FileInputStream("test.zip.003")))));
try {
for(ZipEntry entry = null; (entry = is.getNextEntry()) != null; ) {
OutputStream os = new BufferedOutputStream(new FileOutputStream(entry.getName()));
try {
final int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
for(int readBytes = -1; (readBytes = is.read(buffer, 0, bufferSize)) > -1; ) {
os.write(buffer, 0, readBytes);
}
os.flush();
} finally {
os.close();
}
}
} finally {
is.close();
}
}
}
Just a note to make it more dynamic -- 100% based on mijer code below.
private void CombineFiles (String[] files) throws FileNotFoundException, IOException {
Vector<FileInputStream> v = new Vector<FileInputStream>(files.length);
for (int x = 0; x < files.length; x++)
v.add(new FileInputStream(inputDirectory + files[x]));
Enumeration<FileInputStream> e = v.elements();
SequenceInputStream sequenceInputStream = new SequenceInputStream(e);
ZipInputStream is = new ZipInputStream(sequenceInputStream);
try {
for (ZipEntry entry = null; (entry = is.getNextEntry()) != null;) {
OutputStream os = new BufferedOutputStream(new FileOutputStream(entry.getName()));
try {
final int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
for (int readBytes = -1; (readBytes = is.read(buffer, 0, bufferSize)) > -1;) {
os.write(buffer, 0, readBytes);
}
os.flush();
} finally {
os.close();
}
}
} finally {
is.close();
}
}
To just concatenate the segment data did not work for me. In this case the segments had been created with Linux command-line zip (InfoZip version 3.0):
> zip -s 5m data.zip -r data/
Segment files named data.z01, data.z02, ..., data.zip was created.
The first segment data.z01 contained the spanning signature 0x08074b50, as described in the Zip File Format Specification by PKWARE. The presence of these 4 bytes made Java ZipInputStream ignore all entries in the archive. The central registry in the last segment also contained extra segment information compared to a non-split archive but that did not cause ZipInputStream any problems.
All I had to do was to skip the spanning signature. The following code will extract entries both from an archive that have been segmented with zip -s and from a zip file that have been split by the Linux split commad, like this: split -d -b 5M data.zip data.zip.. The code is based on szhem's.
public class ZipCat {
private final static byte[] SPANNING_SIGNATURE = {0x50, 0x4b, 0x07, 0x08};
public static void main(String[] args) throws IOException {
List<InputStream> asList = new ArrayList<>();
byte[] buf4 = new byte[4];
PushbackInputStream pis = new PushbackInputStream(new FileInputStream(args[0]), buf4.length);
asList.add(pis);
if (pis.read(buf4) != buf4.length) {
throw new IOException(args[0] + " is too small for a zip file/segment");
}
if (!Arrays.equals(buf4, SPANNING_SIGNATURE)) {
pis.unread(buf4, 0, buf4.length);
}
for (int i = 1; i < args.length; i++) {
asList.add(new FileInputStream(args[i]));
}
try (ZipInputStream is = new ZipInputStream(new SequenceInputStream(Collections.enumeration(asList)))) {
for (ZipEntry entry = null; (entry = is.getNextEntry()) != null;) {
if (entry.isDirectory()) {
new File(entry.getName()).mkdirs();
} else {
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(entry.getName()))) {
byte[] buffer = new byte[1024];
int count = -1;
while ((count = is.read(buffer)) != -1) {
os.write(buffer, 0, count);
}
}
}
}
}
}
}

Categories