This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Read Image File Through Java Socket
void readImage() throws IOException
{
socket = new Socket("upload.wikimedia.org", 80);
DataOutputStream bw = new DataOutputStream(new DataOutputStream(socket.getOutputStream()));
bw.writeBytes("GET /wikipedia/commons/8/80/Knut_IMG_8095.jpg HTTP/1.1\n");
bw.writeBytes("Host: wlab.cs.bilkent.edu.tr:80\n\n");
DataInputStream in = new DataInputStream(socket.getInputStream());
File file = new File("imgg.jpg");
file.createNewFile();
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
{
dos.write(buffer, 0, count);
dos.flush();
}
dos.close();
System.out.println("image transfer done");
socket.close();
}
-Create a socket
-Create output stream
-Request the page that includes image
-Read socket to an input stream
-Write to file
I am trying to read an image from socket.
But it is not working.
It seems to read and the image is opened but can not be seen
Where is the problem?
You need to skip HTTP headers to get correct image.
I've already answered to this question today, look at: Read Image File Through Java Socket
The second problem, that you are trying to receive an image from wikipedia without referer and wikipedia restrict to do that (you receiving access denied every time). Try to use another image URL (google image for example).
You can use URL objects directly to fetch HTTP content. The input stream returned by the URL object will only contain content at the URL. The example method below takes a URL, fetches its content and writes the content to a given file.
public static void createImageFile(URL url, File file) throws IOException{
FileOutputStream fos = null;
InputStream is = null;
byte[] b = new byte[1024]; // 1 kB read blocks.
URLConnection conn;
try{
conn = url.openConnection();
/* Set some connection options here
before opening the stream
(i.e. connect and read timeouts) */
is = conn.getInputStream();
fos = new FileOutputStream(file);
int i = 0;
do{
i = is.read(b);
if(i != -1)
fos.write(b, 0, i);
}while(i != -1)
}finally{
/* Don't forget to clean up. */
if(is != null){
try{
is.close();
}catch(Exception e){
/* Don't care */
}
}
if(fos != null){
try{
fos.close();
}catch(Exception e){
/* Don't care */
}
}
}
}
Related
This question already has answers here:
How can I download and save a file from the Internet using Java?
(23 answers)
Closed 8 years ago.
Downloaded Zip files using Java, when it's open saying that Can't open.
Want to know what is the pblm?
Is it because of less memory?
Here is the code for downloading zipFiles
try {
for(int i=0;i<URL_LOCATION.length;i++) {
url = new URL(URL_LOCATION[i]);
connection = url.openConnection();
stream = new BufferedInputStream(connection.getInputStream());
int available = stream.available();
b = new byte[available];
stream.read(b);
File file = new File(LOCAL_FILE[i]);
OutputStream out = new FileOutputStream(file);
out.write(b);
}
} catch (Exception e) {
System.err.println(e.toString());
}
Soln for this: Refered Link is How to download and save a file from Internet using Java?
BufferedInputStream in = null;
FileOutputStream fout = null;
try
{
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
}
}
finally
{
if (in != null)
in.close();
if (fout != null)
fout.close();
}
You are using the available()-call to determine how many bytes to read. Thats blatantly wrong (see javadoc of InputStream for details). available() only tells you about data immediately available, not about the real stream length.
You need a loop and read from the stream until it return -1 (for EndOfStream) as number of bytes read.
I recommend you review the tutorial on streams: http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html
This question already has answers here:
How can I download and save a file from the Internet using Java?
(23 answers)
Closed 4 years ago.
I want to make a Java application that when executed downloads a file from a URL. Is there any function that I can use in order to do this?
This piece of code worked only for a .txt file:
URL url= new URL("http://cgi.di.uoa.gr/~std10108/a.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
PrintWriter writer = new PrintWriter("file.txt", "UTF-8");
String inputLine;
while ((inputLine = in.readLine()) != null){
writer.write(inputLine+ System.getProperty( "line.separator" ));
System.out.println(inputLine);
}
writer.close();
in.close();
Don't use Readers and Writers here as they are designed to handle raw-text files which PDF is not (since it also contains many other information like info about font, and even images). Instead use Streams to copy all raw bytes.
So open connection using URL class. Then just read from its InputStream and write raw bytes to your file.
(this is simplified example, you still need to handle exceptions and ensure closing streams in right places)
System.out.println("opening connection");
URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File("yourFile.jpg"));
System.out.println("reading from resource and writing to file...");
int length = -1;
byte[] buffer = new byte[1024];// buffer for portion of data from connection
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
System.out.println("File downloaded");
Since Java 7 we can also use Files.copy and the try-with-resources to automatically close the InputStream (the stream doesn't have to be closed manually in this case):
URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG");
try (InputStream in = url.openStream()) {
Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// handle exception
}
I'm making a Client-Server. I've gotten as far as that the server can send a hardcoded file, but not a client specified. I will have to send only text files. As far as I have understood: the clients firstly sends the file name and then, the server sends it, nothing complicated, but I'm getting all kinds of errors, this code is getting a connection reset/socket closed error. The main problem is, that hadn't got much time to research networking.
Ill appreciate any help I can get.
EDIT.
I found a work around, closing a stream causes the socket to close, why is that? It shouldn't happen, should it?
Server Side:
InputStream sin=newCon.getInputStream();
DataInputStream sdata=new DataInputStream(sin);
location=sdata.readUTF();
//sdata.close();
//sin.close();
File toSend=new File(location);
byte[] array=new byte[(int)toSend.length()];
FileInputStream fromFile=new FileInputStream(toSend);
BufferedInputStream toBuffer=new BufferedInputStream(fromFile);
toBuffer.read(array,0,array.length);
OutputStream out=newCon.getOutputStream(); //Socket-closed...
out.write(array,0,array.length);
out.flush();
toBuffer.close();
newCon.close();
ClientSide:
int bytesRead;
server=new Socket(host,port);
OutputStream sout=server.getOutputStream();
DataOutputStream sdata=new DataOutputStream(sout);
sdata.writeUTF(interestFile);
//sdata.close();
//sout.close();
InputStream in=server.getInputStream(); //socket closed..
OutputStream out=new FileOutputStream("data.txt");
byte[] buffer=new byte[1024];
while((bytesRead=in.read(buffer))!=-1)
{
out.write(buffer,0,bytesRead);
}
out.close();
server.close();
Try reading the file in chunks from Server while writing to client output stream rather than creating a temp byte array and reading entire file into memory. What if requested file is large? Also close the new Socket on server-side in a finally block so socket is closed even if an exception is thrown.
Server Side:
Socket newCon = ss.accept();
FileInputStream is = null;
OutputStream out = null;
try {
InputStream sin = newCon.getInputStream();
DataInputStream sdata = new DataInputStream(sin);
String location = sdata.readUTF();
System.out.println("location=" + location);
File toSend = new File(location);
// TODO: validate file is safe to access here
if (!toSend.exists()) {
System.out.println("File does not exist");
return;
}
is = new FileInputStream(toSend);
out = newCon.getOutputStream();
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = is.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
} finally {
if (out != null)
try {
out.close();
} catch(IOException e) {
}
if (is != null)
try {
is.close();
} catch(IOException e) {
}
newCon.close();
}
If you use Apache Common IOUtils library then you can reduce much of the code to read/write files to streams. Here 5-lines down to one line.
org.apache.commons.io.IOUtils.copy(is, out);
Note that having a server that serves files by absolute path to remote clients is potentially dangerous and the target file should be restricted to a given directory and/or set of file types. Don't want to serve out system-level files to unauthenticated clients.
Well i am trying to transfer a file using sockets in java
Here is the code
Client Code
try{
// get streams
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream din = new DataInputStream (socket.getInputStream());
dos.writeUTF(fileName);
dos.flush();
boolean isOk = din.readBoolean();
if(!isOk){
throw new StocFileNotFound("Fisierul: " + fileName +" was not found on:" + address.toString());
} else {
baos = new ByteArrayOutputStream();
byte biti [] = new byte[1024];
while(din.read(biti,0,1024) != -1){
baos.write(biti,0,biti.length);
}
}
}
catch(IOException e){}
finally {
try{ socket.close(); } catch (IOException e){}
}
and then I return the baos.toByteArray() and write it to a file with the OutputStream`s write method.
Server code
try{
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream din = new DataInputStream (socket.getInputStream());
// check if it is really a file or if it is an existing file
File file = new File(din.readUTF());
// write false
if ( !file.exists() || !file.isFile() ){
dos.writeBoolean(false);
dos.flush();
}
// write true and write the file
else {
byte biti[] = new byte[1024];
dos.writeBoolean(true);
FileInputStream fis = new FileInputStream(file);
while(fis.read(biti,0,1024) != -1){
dos.write(biti,0,biti.length);
}
dos.flush();
try{ fis.close(); } catch (IOException e){}
}
} catch (IOException e){}
finally {
try{socket.close();}catch(IOException e){}
}
The problem
When i transfer a .txt file and view it in gedit it shows the text followed by multiple \00\00\00, though when i open it using notepad(in wine) it shows only the text. Plus viewing images and .doc works also. So is it something with gedit or is it with my program?
Edit
i was sending something like "hi, hope it works!"
This is the problem (or at least a problem):
while(fis.read(biti,0,1024) != -1)
{
dos.write(biti,0,biti.length);
}
You're always writing out the whole buffer, however many bytes were actually read. You should have:
int bytesRead;
while ((bytesRead = fis.read(biti, 0, 1024)) != -1)
{
dos.write(biti, 0, bytesRead);
}
(You've got the same problem in both bits of code.)
You might want to look at Guava which has various utility methods to relieve you of a lot of the tedium (and possible error) of writing this kind of code over and over again.
The read method will return the actual number of bytes read from the stream. You should use that as a parameter to your write method, or else you will be writing garbage to it.
Hello everyone ,
I am trying to develop the application for transfering/sending the file like SKYPE works.So I am using socket for transfering file from one computer(client) to another computer(client) .I am able to transfer file from one client to server using this. code.But when I try to send the same file from server to second client.It is transfering with 0 byte also give socket close exception so I try to create new socket object at client side.So Now the Exception not coming but file not transfering to client.After debugging I found that the file is successfully sent to client by server but at client side socket is not able to read the data and waiting for data.I can’t find any better solution.If anyone knows anything about this Please tell me.If you have any other solution for file transfer than also tell me.Thanks in advance
Below is my code
Server code:
public class ChatServer
{
serversocket = new ServerSocket(1436);
thread = new Thread(this);
thread.start();
/*************Thread Implementation***************/
public void run()
{
/*********Accepting all the client connections and create a seperate thread******/
while(thread != null)
{
try
{
/********Accepting the Server Connections***********/
socket = serversocket.accept();
/******* Create a Seperate Thread for that each client**************/
chatcommunication = new ChatCommunication(this,socket);
thread.sleep(THREAD_SLEEP_TIME);
}
catch(InterruptedException _INExc) { ExitServer(); }
catch(IOException _IOExc) { ExitServer(); }
}
}
protected void SendGroupFile(Socket ClientSocket, String FileName,String GroupName,String UserName) throws IOException
{
try
{
// receive file from Client
byte [] mybytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(Filepath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =is.read(mybytearray, current, (mybytearray.length-current));
System.out.println("Reading Bytes server"+bytesRead);
if(bytesRead >= 0)
current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray,0,current);
bos.flush();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/***** Function To Send a File to Client **********/
protected void SendGroupFileClient(Socket ClientSocket, String FileName,String GroupName,String UserName)
{
try {
int m_userListSize = userarraylist.size();
clientobject = GetClientObject(GroupName);
if(clientobject != null)
for(G_ILoop = 0; G_ILoop < m_userListSize; G_ILoop++)
{
clientobject = (ClientObject) userarraylist.get(G_ILoop);
if((clientobject.getGroupName().equals(GroupName)) && (!(clientobject.getUserName().equals(UserName))))
{
{
File myFile = new File (Filepath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = socket.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
os.close();
}
}catch(IOException _IOExc)
{
_IOExc.printStackTrace();
}
}
}
ChatCommunication .java
public class ChatCommunication implements Runnable,CommonSettings
{
Thread thread;
Socket socket;
DataInputStream inputstream;
String RFC;
ChatServer Parent;
/********Initialize the Socket to the Client***********/
ChatCommunication(ChatServer chatserver,Socket clientsocket)
{
Parent = chatserver;
socket = clientsocket;
try
{
inputstream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}catch(IOException _IOExc) { }
thread = new Thread(this);
thread.start();
}
public void run()
{
while(thread != null)
{
try {
RFC = inputstream.readLine();
if(RFC.startsWith("FILEGRUP"))
{
Parent.SendGroupFile(socket,RFC.substring(9,RFC.indexOf("!")),RFC.substring(RFC.indexOf("!")+1,RFC.indexOf("*")),RFC.substring(RFC.indexOf("*")+1));
}
if(RFC.startsWith("FILEGET"))
{
Parent.SendGroupFileClient(socket,RFC.substring(8,RFC.indexOf("!")),RFC.substring(RFC.indexOf("!")+1,RFC.indexOf("*")),RFC.substring(RFC.indexOf("*")+1));
}
}catch(Exception _Exc)
{
Parent.RemoveUserWhenException(socket);QuitConnection();
}
}
}
Client code
class Client extends JFrame
{
ServerName="192.168.1.103";
ServerPort=1436;
Client()
{
socket = new Socket(ServerName,ServerPort);
SendGroupFileToServer(Filepath,SelectedGroup);
}
/*******Function To Send File To Server and receiving the file ***********/
protected void SendGroupFileToServer(String FileName, String ToGroup)
{
try {
dataoutputstream.writeBytes(FileName.concat("!").concat(ToUser)+"\r\n");
//send file to sever
File myFile = new File (FileName.substring(9));
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
os.close();
System.out.println("File successfully Sended to server");
}catch(IOException _IoExc) { QuitConnection(QUIT_TYPE_DEFAULT);}
try {
socket1 = new Socket(ServerName,ServerPort); //Creating new Socket
dataoutputstream = new DataOutputStream(socket1.getOutputStream());
dataoutputstream.writeBytes("FILEGET"+FileName.concat("!").concat(ToGroup+"*"+UserName)+"\r\n"); //sending string to server
} catch (IOException e1) {
e1.printStackTrace();
}
// receive file sended by server
byte [] mybytearray = new byte [filesize];
InputStream is;
try {
is = socket1.getInputStream();
FileOutputStream fos = new FileOutputStream(Filepath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead; //up to this working fine
do {
bytesRead =is.read(mybytearray, current, (mybytearray.length-current)); //not reading the file data sent by server just waiting and not go ahead
if(bytesRead >= 0)
current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray,0,current);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are so many problems here that it is difficult to know where to start.
The thread.sleep() in the accept() loop is literally a waste of time. It serves no useful purpose except possibly to throttle the rate at which clients are accepted. If that wasn't your intention, don't do it.
All you are doing when you catch an exception is exiting the server without even printing the exception message. So when something goes wrong, as it is here, you can't possibly know what it was. Don't do that.
readLine() returns null at EOS, on which you must close the socket, stop reading, and exit the thread. You aren't testing that, and you are therefore omitting all three of those required steps. Don't do that.
You are constructing a DataInputStream around a BufferedInputStream for use when reading commands, but you aren't passing it to the methods that process those commands. You are just passing the socket. You are therefore losing data. Don't do that. Every part of the program must use the same input stream or reader for the socket.
You are reading the entire file into memory. This (a) assumes the file size fits into an int; (b) does not scale to large files; (c) wastes space, and (d) adds latency. Don't do that.
You are ignoring the result of the read() into that buffer and assuming it was filled. You can't do that. The correct way to copy streams in Java is shown below. This works with a buffer of any size, e.g. 8192, for an input of any length, and doesn't require you to buffer the entire input into memory. You can use this loop at both the client when sending the file and at the server when receiving it.
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Similarly to (4) above, you are using a DataOutputStream around a BufferedOutputStream for some things and the socket output stream directly for others. Don't do that. All parts of the program must the same output stream or writer for the socket.
You don't need to flush() before close(); it happens automatically.
For some reason after sending the file you are creating a new connection and sending another command. You aren't even closing the connection afterwards. The server will have no easy way of knowing that this connection and this command referred to the file just sent in the code above. It is also redundant, as the receipt of the final EOS tells the server that the file has been sent successfully. Don't do this. If you need to send more information with the file, send it first, before the file, on the same connection.
The reference you cite exhibits many of the above issues. Make an effort to find a reputable starting point.
This is the solution. Please Apply this logic to your code.
I am able to send a file from server to client and client to server.
Check the following code to send the file from Client to Server. It is working great.
If you have any issues let me know.
Server Side Code:
public class ServerRecieveFile {
public static void main(String[] args) throws IOException {// TODO Auto-enerated method stub int filesize=1022386;
int bytesRead; int currentTot= ;
ServerSocket serverSocket=new ServerSocket(15123);
Socket socket=rverSocket.accept();
byte [] bytearray = new byte [filesize];
InputStream is=socket.getInputStream();
File copyFileName=new File("c:/Files Sockets/2.txt");
FileOutputStream fos = new FileOutputStream(copyFileName);
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();
}
}
Client Side code:
public class ClientSendFile {
public static void main(String[] args) throws UnknownHostException, IOException {// TODO Auto-generated method stub
Client client=new Client();
Socket socket = new Socket(InetAddress.getLocalHost(),15123);
System.out.println("Accepted connection : " + socket);
File transferFile = new File ("c:/Files Sockets/1.txt");
byte [] bytearray = new byte (int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
}