I am trying to move the file from the source file to automatically be saved to desktop. Essentially this is an incoming file and I want it where its visible to the user which is his/her desktop I thought I was on the right track but this code doesn't work and previous modifications does not work either can someone point me in the right direction?
System.out.println("Waiting For File......");
int filesize = 6022386;
byte[] mybytearray = new byte[filesize];
InputStream is;
is = connection_download.getInputStream();
FileOutputStream fos;
// obtain header (fileName)
DataInputStream clientData = new DataInputStream(is);
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(fileName);
System.out.println(fileName);
fos = new FileOutputStream(fileName);
BufferedOutputStream 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(fileName.length());
long end = System.currentTimeMillis();
System.out.println("DONE");
bos.close();
// complete file
complete = new File(fileName);
if (isMacOs == true) {
downloadMac(complete);
} else if (isWindowsOS == true) {
downloadWindows(complete);
}
} catch (IOException ex) {
Logger.getLogger(downloadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void downloadMac(File complete) {
JOptionPane.showMessageDialog(null, "Your Files Will be Saved To Your Desktop");
String OS_Path = System.getProperty("user.home");
String savedLocation = OS_Path + "/Desktop/" + complete;
File downloadedLocation = new File(savedLocation);
System.out.println(downloadedLocation);
}
Related
So im making a client-server based architecture programm where server is sending a file and client receives it.
I have seen a lot of code parts and i also made a lot where i send small files. ex images. In my case i want to send .wav audio files which are large(40mb). This is what i have done so far. When i run my client, it just proceed to download, but never really downloads the file. I guess its because its too large.
How to send such large files?
server
public void send_file_to_client(String requested_file) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
File FILE_TO_SEND = new File("C:\\ServerMusicStorage\\" + requested_file + ".wav");
byte[] mybytearray = new byte[(int) FILE_TO_SEND.length()];
try {
fis = new FileInputStream(FILE_TO_SEND);
bis = new BufferedInputStream(fis);
} catch (FileNotFoundException ex) {
Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
}
OutputStream os = null;
bis.read(mybytearray, 0, mybytearray.length);
os = connsock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
toClient.writeUTF(Integer.toString(mybytearray.length));
os.write(mybytearray, 0, mybytearray.length);
os.flush();
System.out.println("Done.");
if (bis != null) {
bis.close();
}
if (os != null) {
os.close();
}
if (connsock != null) {
connsock.close();
}
}
client
public static void receive_file(String requested_file) throws IOException {
File file_to_save = new File("C:\\ClientMusicStorage\\" + requested_file + ".wav");
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
//get file size to create the bytearray
String fileSize=fromServer.readUTF();
int final_file_size = Integer.parseInt(fileSize);
byte[] mybytearray = new byte[final_file_size];
InputStream is = clientSocket.getInputStream();
fos = new FileOutputStream(file_to_save);
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();
}
I'm making simple Client-Server application to make file copies on server.
There is clientside method for sending file to server:
private void makeCopy(Socket clientSock) throws IOException {
File file = new File("D:\\client\\toCopy.bmp");
File dest = new File("D:\\server\\copyFile.bmp");
boolean ifExists = dest.exists();
if(ifExists && !file.isDirectory()){
System.out.println("Copy is already made on server.");
}
else{
fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
while (fis.read(buffer) > 0) {
oos.write(buffer);
}
//fis.close();
oos.close();
}
}
Also there is serverside method for receiving file from client:
public void saveFile(Socket s) throws IOException{
File copy = new File("D:\\server\\fileCopy.bmp");
fos = new FileOutputStream(copy);
File fromServer = new File("D:\\client\\toCopy.bmp");
if(copy.exists() && !copy.isDirectory()){
}
else{
byte[] buffer = new byte[4096];
int filesize = (int)fromServer.length();
int read = 0;
int totalRead = 0;
int remaining = filesize;
while((read = ois.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
}
}
The problem is, even if i check file existance it still makes file which I can't open (it has 0 bytes written). Any ideas ?
FileOutputStream creates a file output stream and a file in a file system.
First you should check existence and then create FileOutputStream.
File copy = new File("D:\\server\\fileCopy.bmp");
if(copy.exists() && !copy.isDirectory()){ }
fos = new FileOutputStream(copy);
File fromServer = new File("D:\\client\\toCopy.bmp");
I am trying to transfer a large file from a server to a client. My code so far works but only if I set the buffer size in the client code to the exact size of the file. I won't always know what the file size is going to be. I keep finding examples that claim it doesn't matter what the size of the file or buffer is because it will just keep reading from the input stream...? However, when I implement the code that supposedly does this, it transfers 0 bytes.
Client:
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(hostname, 20000);
System.out.println("Connecting...");
// receive file
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVE);
bos = new BufferedOutputStream(fos);
//////////// replaced this ////////////////////////////
byte[] buffer = new byte[BUFFER_SIZE];
bytesRead = is.read(buffer,0,buffer.length);
current = bytesRead;
do {
bytesRead = is.read(buffer, current, (buffer.length-current));
if(bytesRead >= 0){ current += bytesRead;}
} while(bytesRead > 0);
bos.write(buffer, 0 , current);
///////////////////////////////////////
// with this:
// int count;
// byte[] buffer = new byte[8192];
// while ((count = is.read(buffer)) > 0)
// {
// bos.write(buffer, 0, count);
// }
//////////// transfers 0 bytes ///////////
bos.flush();
System.out.println("File " + FILE_TO_RECEIVE
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null){ fos.close();}
if (bos != null){ bos.close();}
if (sock != null){ sock.close();}
}
}
Server:
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(20000);
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.");
}
finally {
if (bis != null){ bis.close();}
if (os != null){ os.close();}
if (sock!=null){ sock.close();}
}
}
}
finally {
if (servsock != null){
servsock.close();
}
}
}
Thank you for your help
Your copy loops are both different, and both nonsense. One of them isn't even a loop. Try this:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
This works for any buffer of size >= one byte.
Use this at both ends.
My server is sending several files to my client. However at the client side, it only receives the first file because I don't know how to iterate and get the second file.
The Server sends like this:
ListIterator iter = missingfiles.listIterator();
//missingfiles contain all the filenames to be sent
String filename;
while (iter.hasNext()) {
// System.out.println(iter.next());
filename=(String) iter.next();
File myFile = new File("src/ee4210/files/"+filename);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//bis.read(mybytearray, 0, mybytearray.length);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = _socket.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
}
The client receives like this: (It will only receive the first file and I don't know how to make it loop to receive the next file)
int bytesRead;
int current = 0;
int filecount = 0;
InputStream in;
try {
in = _socket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(
"src/ee4210/files/"+ fileName);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0
&& (bytesRead = clientData.read(buffer, 0,
(int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
How to receive multiple files from outputstream?
The obvious answer is 'one at a time, with extra information to tell you where one stops and another starts'. The most usual technique is to send the file size ahead of the file, e.g. as a long via DataOutputStream.writeLong(), and at the receiver change your read loop to stop after exactly that many bytes, close the output file, and continue the outer loop that reads the next long or end-of-stream.
You can try this.
I've used a lazy method to check that the end of all 3 files have been received.
int bytesRead;
int current = 0;
int filecount = 0;
InputStream in;
try
{
in = _socket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
while(true)
{
String fileName = clientData.readUTF();
// will throw an EOFException when the end of file is reached. Exit loop then.
OutputStream output = new FileOutputStream("src/ee4210/files/"+ fileName);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0
&& (bytesRead = clientData.read(buffer, 0,
(int) Math.min(buffer.length, size))) != -1)
{
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
}
}
catch (EOFException e)
{
// means we have read all the files
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
hello guys i have designed a server client which transfers data through sockets. Everything is ok when i run it on my machine it works 100% of the time. When i run the server on another machine and the client on mine, i am unable to get data. when i run the server on my machine and the client on theirs i am unable to put data , but i can get. i dont know what is going on, maybe you can shed some light.
There is more code that makes this work correctly but i omit that out to reduce the complications . Please if you get a chanse look at this and tell me why it works on my system but not on the server? and does anyone know how to debug this? i mean this is run on the server how can i debug a server since i cannot be there (and everything works correctly on my system?)
Server :
if (get.equals("get")) {
try {
Copy copy = new Copy(socket, dir);//maybe dir is not needed
String name = input.substring(4);
File checkFile = new File(dir.getCurrentPath(), name);
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
if (checkFile.isFile() && checkFile.exists()) {
outToClient.writeBytes("continue" + "\n");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
boolean cont = false;
String x;
while (!cont) {
if ((x = inFromServer.readLine()).equals("continue")) {
cont = true;
}
}
copy.copyFile(name);
output = "File copied to client successfully" + "\n";
} else {
outToClient.writeBytes("File failed to be copied to client" + "\n");
output = "";
}
} catch (Exception e) {
output = "Failed to Copy File to client" + "\n";
}
} else if (get.equals("put")) {
//so the client sends: the put request
//then sends the length
try {
DataInputStream inFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
outToClient.writeBytes("continue" + "\n");
long lengthLong = (inFromClient.readLong());
int length = (int) lengthLong;
byte[] recieveFile = new byte[length];//FIX THE LENGTH
// InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("Copy " + input.substring(4));
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead;
int current = 0;
bytesRead = inFromClient.read(recieveFile, 0, recieveFile.length);
current = bytesRead;
do {
bytesRead = inFromClient.read(recieveFile, current, (recieveFile.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > 0); // FIX THE LENGTH
bos.write(recieveFile, 0, current);
bos.flush();
bos.close();
output = "File copied to Server successfully" + " \n";
The copy class:
File checkFile = new File(dir.getCurrentPath(), file);
if (checkFile.isFile() && checkFile.exists()) {
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
// byte[] receivedData = new byte[8192];
File inputFile = new File(dir.getCurrentPath(), file);
byte[] receivedData = new byte[(int) inputFile.length()];
long length = inputFile.length();
outToClient.writeLong(length);
//maybe wait here for get request?
DataInputStream dis = new DataInputStream(new FileInputStream(getCopyPath(file)));
dis.read(receivedData, 0, receivedData.length);
OutputStream os = socket.getOutputStream();
outToClient.write(receivedData, 0, receivedData.length);//outputStreasm replaced by Datatoutputstream
outToClient.flush();
The client class:
else if (sentence.length() > 3 && sentence.substring(0, 3).equals("get")) {
outToServer.writeBytes(sentence + "\n");
String response = inFromServer.readLine();
if (response.equals("File failed to be copied to client")) {
System.out.println(response);
} else {
DataInputStream inFromClient = new DataInputStream(clientSocket.getInputStream());
DataOutputStream outToClient = new DataOutputStream(clientSocket.getOutputStream());
outToClient.writeBytes("continue" + "\n");
long lengthLong = (inFromClient.readLong());
int length = (int) lengthLong;
byte[] recieveFile = new byte[length];
FileOutputStream fos = new FileOutputStream("Copy " + sentence.substring(4));
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead;
int current = 0;
bytesRead = inFromClient.read(recieveFile, 0, recieveFile.length);
current = bytesRead;
do {
bytesRead = inFromClient.read(recieveFile, current, (recieveFile.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > 0);
bos.write(recieveFile, 0, current);
bos.flush();
bos.close();
}
} else if (sentence.length() > 3 && sentence.substring(0, 3).equals("put")) {
File checkFile = new File(dir.getCurrentPath(), sentence.substring(4));
if (checkFile.isFile() && checkFile.exists()) {
try {
outToServer.writeBytes(sentence + "\n");
boolean cont = false;
String x;
while (!cont) {
if ((x = inFromServer.readLine()).equals("continue")) {
cont = true;
}
}
String name = sentence.substring(4);
copy.copyFile(name);