I have a function for html page download.
Here is the code:
public class pageDownload {
public static void down(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(new File(filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
in.close();
fout.close();
}
}
Works ok, problem appears when i try to download a page that not exist. I can't figure out how to handle 404 error in this case.
Has anyone some idea?
Do you mean something like this? I added a finally to save close the Streams
public class pageDownload {
public static void down(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(new File(filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch(FileNotFoundException ex)
{
System.err.println("Caught 404: " + e.getMessage());
}
catch(IOException ex)
{
System.err.println("Caught IOException: " + e.getMessage());
}
catch(IndexOutOfBoundsException e)
{
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
finally{
if(in != null)
try { in.close(); } catch ( IOException e ) { }
if(fout != null)
try { fout.close(); } catch ( IOException e ) { }
}
}
}
Your problem is you get a NullPointerException when you try to close the streams. You should anyway close them in a finally clause or use try with resources:
public static void down(final String filename, final String urlString)
throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new URL(urlString)
.openStream());
FileOutputStream fout = new FileOutputStream(new File(filename))) {
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
}
Related
I am making a multiplayer drawing application for android and I need to send the drawings that every user made to one player. I am using a server socket for this.
First thing I do is convert the Bitmap to a byte array, so I can send it to the Host with host.write(byteArray);
Bitmap bitmapImage = drawView.getBitmap();
byte[] byteArray = getByteArray(bitmapImage);
byteArrayLength = byteArray.length;
MainWifiActivity.SendReceive host = MainWifiActivity.sendReceiveHost;
if (host != null) {
host.write(byteArray);
}
The following code is my SendReceive class, which listenes to the inputStream and then starts a Handler, that is supposed to save the Bitmap to Internal Storage
public class SendReceive extends Thread {
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket s) {
socket = s;
try {
inputStream = s.getInputStream();
outputStream = s.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
int filesize;
while (socket != null) {
try {
filesize = DrawingActivity.byteArrayLength;
if(buffer.length != filesize && filesize > 0){
buffer = new byte[filesize];
}
bytes = inputStream.read(buffer,0 ,buffer.length);
if (bytes > 0) {
Message mesg = handler.obtainMessage(IMAGE_MSG, bytes, -1, buffer);
mesg.sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And the Handler:
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case IMAGE_MSG:
byte[] byteArray = (byte[]) msg.obj;
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
saveBitmapToInternalStorage(bitmap);
}
return false;
}
});
In the saveBitmapToInternalStorage Method I get a java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
private void saveBitmapToInternalStorage(Bitmap bmp) {
File directory = getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory, UUID.randomUUID().toString() + ".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
Log.d("HELLO", "MY ERROR: " + e);
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I know that BitmapFactory.decodeByteArray returns the decoded bitmap, or null if the image could not be decoded.
But why could it not be decoded?
I think this piece is wrong
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
It should be
FileOutputStream fos = new FileOutputStream(myPath);
try {
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
I am using plupload at JavaScript library.
I want to resume file uploads if there is a failure while implementing file uploads.
I've been told to use HTTP chunk transfer.
but I don't know, How can I use it.
please show following server-side code.
private static final int BUFFER_SIZE = 100 * 1024;
try {
Integer chunk = 0, chunks = 0;
if(null != request.getParameter("chunk") && !request.getParameter("chunk").equals("")){
chunk = Integer.valueOf(request.getParameter("chunk"));
}
if(null != request.getParameter("chunks") && !request.getParameter("chunks").equals("")){
chunks = Integer.valueOf(request.getParameter("chunks"));
}
logger.info("chunk:[" + chunk + "] chunks:[" + chunks + "]");
...
appendFile(file.getInputStream(), destFile, response);
if (chunk == chunks - 1) {
logger.info("upload success !");
}else {
logger.info("left ["+(chunks-1-chunk)+"] chunks...");
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
public void appendFile(InputStream in, File destFile, HttpServletResponse response) {
OutputStream out = null;
try {
if (destFile.exists()) {
out = new BufferedOutputStream(new FileOutputStream(destFile, true), BUFFER_SIZE);
} else {
out = new BufferedOutputStream(new FileOutputStream(destFile),BUFFER_SIZE);
}
in = new BufferedInputStream(in, BUFFER_SIZE);
int len = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
logger.error(e.getMessage());
}
finally {
try {
if (null != in) {
in.close();
}
if(null != out){
out.close();
}
} catch (IOException e) {
e.getMessage();
logger.error(e.getMessage());
}
}
}
I am trying to build a client server model in java using sockets to share files.
It works fine for one iteration of loop for sending a file but after that no data is received on the server. Please take a look at my code and suggest me something to correct this.
FileClient.java
public class FileClient {
private void listFiles() {
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
while (dis.available() > 0) {
System.out.println(dis.readUTF());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void selectAndDownloadFiles() {
}
private Socket s;
public FileClient(String host, int port) {
try {
s = new Socket(host, port);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendFile(String file) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
File myFile = new File (file);
dos.writeUTF(file);
dos.writeInt((int)myFile.length());
try {
sleep(2);
} catch (InterruptedException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = new byte[8192];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
}
public static void main(String[] args) {
int choice = 0;
Scanner in = new Scanner(System.in);
FileClient fc = new FileClient("localhost", 1988);
DataOutputStream dos = null;
try {
dos = new DataOutputStream(fc.s.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
do {
try {
System.out.println("Choose an action to perform..!");
System.out.println("1. List the files..");
System.out.println("2. Select and download files");
System.out.println("3. Send a file..");
System.out.println("0. Exit..");
choice = in.nextInt();
String fileName;
switch (choice) {
case 1:
try {
dos.write(choice);
System.out.println("List Files Request Sent..!");
} catch (IOException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
sleep(2);
fc.listFiles();
break;
case 2:
selectAndDownloadFiles();
break;
case 3:
try {
dos.write(choice);
} catch (IOException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Enter file name to send");
fileName = in.next();
try {
fc.sendFile(fileName);
} catch (IOException ex) {
ex.printStackTrace();
}
break;
case 0:
System.exit(0);
break;
default:
System.out.println();
}
} catch (InterruptedException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
} while (choice != 0);
}
}
FileServer.java
public class FileServer extends Thread {
private static ServerSocket ss;
public FileServer(int port) {
try {
ss = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
File theDir = new File("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles");
// if the directory does not exist, create it
if (!theDir.exists()) {
boolean result = false;
try {
theDir.mkdir();
result = true;
} catch (SecurityException se) {
//handle it
}
if (result) {
System.out.println("DIR created");
}
}
while (true) {
try {
Socket clientSock = ss.accept();
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
DataOutputStream dos = new DataOutputStream(clientSock.getOutputStream());
int choice;
while ((choice = dis.read()) > 0) {
switch (choice) {
case 1:
System.out.println("List Files Request Received..!");
listFiles(clientSock);
System.out.println("List Files Response Sent..!");
break;
case 2:
sendSelectedFiles();
break;
case 3:
saveFile(clientSock);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveFile(Socket clientSock) throws IOException {
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
String fileName = dis.readUTF();
int filesize = dis.readInt();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles\\" + fileName);
try {
sleep(2);
} catch (InterruptedException ex) {
Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = new byte[8192];
// Send file size in separate msg
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
//fos.close();
//dis.close();
}
public static void main(String[] args) {
FileServer fs = new FileServer(1988);
fs.start();
}
private void listFiles(Socket clientSock) {
File folder = new File("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles");
File[] listOfFiles = folder.listFiles();
try {
DataOutputStream dos = new DataOutputStream(clientSock.getOutputStream());
if (listOfFiles.length > 0) {
for (int i = 0; i < listOfFiles.length; i++) {
dos.writeUTF(listOfFiles[i].getName());
}
} else {
dos.writeUTF("There are no files on the server..!");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void sendSelectedFiles() {
}
}
Attached are the images of output.
public void decrypt(String inputFile, String password) {
ZipDecryptInputStream zipDecrypt = null;
try {
zipDecrypt = new ZipDecryptInputStream(new FileInputStream(
inputFile), password);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File file = new File("outouttfile.tsv");
OutputStream fop = null;
try {
fop = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zipDecrypt.read(buffer)) != -1) {
fop.write(buffer, 0, bytesRead);
System.out.println("Written");
}
} catch (IOException e) {
e.printStackTrace();
}
}
My while loop becomes an infinite loop and does not stop reading the file even its read once. Any idea why?
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
package main;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.Socket;
public class FileTransfer {
private Socket socket;
private static final int MAX_BUFFER = 8192;
public FileTransfer(Socket socket) {
this.socket = socket;
}
public boolean sendFile(File file) {
boolean errorOnSave = false;
long length = file.length();
if (file.exists()) {
FileInputStream in = null;
DataOutputStream out = null;
try {
in = new FileInputStream(file);
out = new DataOutputStream(this.socket.getOutputStream());
out.writeLong(length);
out.flush();
byte buffer[] = new byte[MAX_BUFFER];
int read = 0;
int i=0;
while ((read = in.read(buffer)) != -1) {
System.out.println(i);
i++;
out.write(buffer, 0, read);
out.flush();
buffer = new byte[MAX_BUFFER];
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return false;
} catch (IOException e) {
System.out.println("An error has occurred when try send file " + file.getName() + " \nSocket: "
+ socket.getInetAddress() + ":" + socket.getPort() + "\n\t" + e);
errorOnSave = true;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println("An error has occurred when closing the InputStream of the file "
+ file.getName() + "\n\t" + e.getMessage());
}
}
}
return !errorOnSave;
} else {
return false;
}
}
public boolean saveFile(File fileSave) {
RandomAccessFile file = null;
DataInputStream in = null;
boolean errorOnSave = false;
try {
file = new RandomAccessFile(fileSave, "rw");
file.getChannel().lock();
in = new DataInputStream(this.socket.getInputStream());
long fileSize = in.readLong();
byte buffer[] = new byte[MAX_BUFFER];
int read = 0;
while ((fileSize > 0) && ((read = in.read(buffer, 0, (int) Math.min(buffer.length, fileSize))) != -1)) {
file.write(buffer, 0, read);
fileSize -= read;
buffer = new byte[MAX_BUFFER];
}
} catch (FileNotFoundException e1) {
System.out.println(e1.getMessage());
return false;
} catch (IOException e) {
System.out.println("An error has occurred when saving the file\n\t" + e.getMessage());
errorOnSave = true;
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println(
"An error occurred when closing the file " + fileSave.getName() + "\n\t" + e.getMessage());
errorOnSave = true;
}
}
if (errorOnSave) {
if (fileSave.exists()) {
fileSave.delete();
}
}
}
return !errorOnSave;
}
}
I have a problem with my java project(its going to send files from server to client...) its always telling me after a few seconds
"Connection reset by peer: socket write error" if someone has the answear please tell whats wrong with my code.....
I had this issue recently: Try this
setBufferSize(1024*1024);
setKeepAlive(false);
Also check if you are on the same WLAN connection (both your device and the server itself)
I hope this helps you get something going!