FileOutputStream creates file even if i check file existance - java

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");

Related

Code that download empty file and supposed not to

I have this part of function where it supposed to download file like pdf from server and store in new directory. It does do this but an empty pdf or text file.How to fix it.
`File urlfile = new File(host + "/" + path);
urlfile.getParentFile().mkdirs();
// create outputstream for request and inputstream for data
// download
FileOutputStream outS = new FileOutputStream(urlfile);
DataInputStream instream = new DataInputStream(newsocket.getInputStream());
// get rid of head part to get to actual file
String l = null;
String lastmodtime = null;
boolean done = false;
while (!(l = DAA.readLine()).equals("")) {
if (!done && l.contains("Last-Modified:")) {
lastmodtime = l.substring(l.indexOf(' ') + 1, l.length());
done = true;
System.out.println(l);
}
}
// read in bytes to correct file name
try {
byte[] inbytes = new byte[16384];
int input;
while ((input = instream.read(inbytes)) != -1) {
outS.write(inbytes, 0, input);
}
}`
You can try this simple code if you want to create a copy of the file or you can even use apache commons io (FileUtils.copyFile(source, dest)) for java copy file operation.
private static void copyFileUsingStream(File source, File dest)
throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}

Path in client-server application to file transfer JAVA

I have problem with my application server-client to file transfer in java.
In client side I choose path to file by FileDialog and send to server but I don't know how can I set path in server side.
Which will be path for this sending file?
Client side:
try {
FileDialog fd =new FileDialog(this,"Select",FileDialog.LOAD);
fd.setVisible(true);
String katalog=fd.getDirectory();
String plik=fd.getFile();
pw.println(plik);
infoPlik2.setText(plik);
jta.setText("");
jta.append("File: " + plik);
jta.append("in directory: "+ katalog);
FileInputStream fis = new FileInputStream(plik);
byte[] buffer = new byte[1024];
int bytes = 0;
long start = System.currentTimeMillis();
while ((bytes = fis.read(buffer)) >0) {
out.write(buffer, 0, bytes);
}
long end = System.currentTimeMillis();
double kbps = (double) bytes / (end - start);
sFile2.setText("Speed: " + kbps + " kbps");
fis.close();
} catch (Exception exx) {
System.out.println(exx.getMessage());
}
Server side:
try {
//File f = new File() ???????????????
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int count;
InputStream ins = incoming.getInputStream();
while ((count = ins.read(buffer)) > 0) {
fos.write(buffer);
}
fos.close();
incoming.close();
Something like that, please help me how can I resolve this problem.
Your code only transfers content.
what you lack is transfering file name/path. Send it before or after.

Reading JPEG Stream over socket gives Null characters

I am reading a .jpg file over InputStream using this code but I am receiving NULNUL...n stream after some text. Ii am reading this file link to file and link of file that I received , link is Written File link.
while ((ret = input.read(imageCharArray)) != -1) {
packet.append(new String(imageCharArray, 0, ret));
totRead += ret;
imageCharArray = new char[4096];
}
file = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
PrintWriter printWriter = new PrintWriter(file);
// outputStream = new FileOutputStream(file); //also Used FileoutputStream for writting
// outputStream.write(packet.toString().getBytes());//
// ,
printWriter.write(packet.toString());
// outputStream.close();
printWriter.close();
}
I have also tried FileoutputStream but hardlucj for this too as commented in my code.
Edit
I have used this also. I have a content length field upto which i am reading and writing
byte[] bytes = new byte[1024];
int totalReadLength = 0;
// read untill we have bytes
while ((read = inputStream.read(bytes)) != -1
&& contentLength >= (totalReadLength)) {
outputStream.write(bytes, 0, read);
totalReadLength += read;
System.out.println(" read size ======= "
+ read + " totalReadLength = "
+ totalReadLength);
}
String is not a container for binary data, and PrintWriter isn't a way to write it. Get rid of all, all, the conversions between bytes and String and vice versa, and just transfer the bytes with input and output streams:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
If you need to constrain the number of bytes read from the input, you have to do that before calling read(), and you also have to constrain the read() correctly:
while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length: (int)(length-total))) > 0)
{
total += count;
out.write(buffer, 0, count);
}
I tested it in my Nexus4 and it's working for me. Here is the snippet of code what I tried :
public void saveImage(String urlPath)throws Exception{
String fileName = "kumar.jpg";
File folder = new File("/sdcard/MyImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder,
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection().getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with bytes from the data input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Just Call the above function in a background thread and pass your url. It'll work for sure. Let me know if it helps.
You can check below code.
destinationFile = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte byt[] = new byte[1024];
int i;
for (long l = 0L; (i = input.read(byt)) != -1; l += i ) {
buffer.write(byt, 0, i);
}
buffer.close();

How to return and delete file?

I want to return file (read or load) from method and then remove this file.
public File method() {
File f = loadFile();
f.delete();
return f;
}
But when I delete a file, I delete it from disk and then exists only descriptor to non-existing file on return statement. So what is the most effective way for it.
You can't keep the File handle of deleted file, rather you can keep the data in a byte array temporarily, delete the file and then return the byte array
public byte[] method() {
File f =loadFile();
FileInputStream fis = new FileInputStream(f);
byte[] data = new byte[fis.available()];
fis.read(data);
f.delete();
return data;
}
// Edit Aproach 2
FileInputStream input = new FileInputStream(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int bytesRead = input.read(buf);
while (bytesRead != -1) {
baos.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
}
baos.flush();
byte[] bytes = baos.toByteArray();
you can construct the file data from byte array
However, my suggestion is to use IOUtils.toByteArray(InputStream input) from Jakarta commons, why do you want re write when already in plate
Assuming you want to return the file to the browser, this is how I did it :
File pdf = new File("file.pdf");
if (pdf.exists()) {
try {
InputStream inputStream = new FileInputStream(pdf);
httpServletResponse.setContentType("application/pdf");
httpServletResponse.addHeader("content-disposition", "inline;filename=file.pdf");
copy(inputStream, httpServletResponse.getOutputStream());
inputStream.close();
pdf.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
private static int copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[512];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}

Zip a file in BlackBerry Java app

Does anyone know how to zip a file using ZipOutputStream?
try {
// Creating Zip Streams
FileConnection path = (FileConnection) Connector.open(
"file:///SDCard/BlackBerry/documents/" + "status.zip",
Connector.READ_WRITE);
if (!path.exists()) {
path.create();
}
ZipOutputStream zinstream = new ZipOutputStream(
path.openOutputStream());
// Adding Entries
FileConnection jsonfile = (FileConnection) Connector.open(
"file:///SDCard/BlackBerry/documents/" + "status.json",
Connector.READ_WRITE);
if (!jsonfile.exists()) {
jsonfile.create();
}
int fileSize = (int) jsonfile.fileSize();
if (fileSize > -1) {
byte[] data = new byte[fileSize];
InputStream input = jsonfile.openInputStream();
input.read(data);
ZipEntry entry = new ZipEntry(jsonfile.getName());
zinstream.putNextEntry(entry);
// zinstream.write(buf);
// ZipEntry entry = null;
path.setWritable(true);
OutputStream out = path.openOutputStream();
int len;
while ((len = input.read(data)) != -1) {
out.write(data, 0, len);
out.flush();
out.close();
zinstream.close();
content = "FILE EXIST" + entry;
}
jsonfile.close();
path.close();
}
} catch (...) {
...
}
The data should be written to the ZipOutputStream zinstream instead of to a new OutputStream out.
Its also important to close the ZipEntry entry after writing is done.
FileConnection path = (FileConnection) Connector.open(
"file:///SDCard/BlackBerry/documents/" + "status.zip",
Connector.READ_WRITE);
if (!path.exists()) {
path.create();
}
ZipOutputStream zinstream = new ZipOutputStream(path.openOutputStream());
// Adding Entries
FileConnection jsonfile = (FileConnection) Connector.open(
"file:///SDCard/BlackBerry/documents/" + "status.json",
Connector.READ_WRITE);
if (!jsonfile.exists()) {
jsonfile.create();
}
int fileSize = (int) jsonfile.fileSize();
if (fileSize > -1) {
InputStream input = jsonfile.openInputStream();
byte[] data = new byte[1024];
ZipEntry entry = new ZipEntry(jsonfile.getName());
zinstream.putNextEntry(entry);
int len;
while ((len = input.read(data)) > 0) {
zinstream.write(data, 0, len);
}
zinstream.closeEntry();
}
jsonfile.close();
zinstream.close();
path.close();
BlackBerry uses the J2ME API which does not have all of the J2SE classes, such as the ZipOutputStream and ZipEntry and related classes. There are some classes such as ZLibOutputStream which may help, but that is just the byte-level compression and you'll end up having to implement the actual PKZIP container yourself (unless there is a third-party library out there that can do this for you).

Categories

Resources