On a server hosted on google app engine, I am trying to download files from another server, zip (using util.zip) them and upload the zip file for later download.
I have files in a folder (html and png files). The download and zip and upload is successful. I can download the desired zip, however I can not open the png files, even though I can the original ones. It says the program doesn't support the file format. Interestingly the there are no problems with the html files in the zip.
Does anybody know what can be the problem here?
Thank you in advance.
--THE CODE--
public boolean generateZip(){
byte[] application = new byte[1500000];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(baos);
//This will get the desired file names and locations from the other server
ArrayList<String> others = getFileNames(this);
for(String s: others){
URL url = new URL("http://otherserver.com/" + s);
BufferedReader reader = null;
try{
//I need only the file names not the full directory name
int toSub = s.lastIndexOf("/");
String entryString = s.substring(toSub+1);
out.putNextEntry(new ZipEntry(entryString));
reader = new BufferedReader(new InputStreamReader(url.openStream()));
byte[] buffer = new byte[3000000];
int bindex = 0;
int b = reader.read();
while(b != -1){
buffer[bindex] = (byte) b;
bindex++;
b = reader.read();
}
out.write(buffer,0,bindex);
out.closeEntry();
reader.close();
System.out.println(entryString + " packaged...");
}catch(Exception e){
e.printStackTrace();
}
}
}
out.close();
} catch (IOException e) {
System.out.println("There was an error generating ZIP.");
e.printStackTrace();
}
return uploadZip(baos.toByteArray());
}
Finally I found the solution. For anyone who's interested:
for(String s: others){
URL url = new URL("http://otherserver.com" + s);
System.out.println("Reading " + s);
try{
int toSub = s.lastIndexOf("/");
String entryString = s.substring(toSub+1);
out.putNextEntry(new ZipEntry(entryString));
BufferedInputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
BufferedOutputStream out2 = new BufferedOutputStream(baos2);
int i;
while ((i = in.read()) != -1) {
out2.write(i);
}
out2.flush();
byte[] data = baos2.toByteArray();
// closing all the shits
out2.close();
in.close();
out.write(data,0,data.length);
out.closeEntry();
System.out.println(entryString + " packaged...");
}catch(Exception e){
e.printStackTrace();
}
}
Related
Hello everyone.
Ask this question so that they could give me a hand and guide me on my way.
My problem
I want to be able to unzip a zip into a folder or directory on the SD card, but my code has not reached the target. Its error is that it does not decompress or copy any of the files in the destination directory. The zip is located in the resources resource folder.
My code
private boolean copyFile1(String filename1, String outPath1) {
AssetManager assetManager = this.getAssets();
final int CHUNK_SIZE = 1024 * 4;
InputStream in;
OutputStream out;
try {
in = assetManager.open(filename1);
String newFileName = outPath1;
ZipInputStream zipStream = new ZipInputStream(in);
ZipEntry zEntry = null;
while ((zEntry = zipStream.getNextEntry()) != null) {
if (zEntry.isDirectory()) {
} else {
FileOutputStream fout = new FileOutputStream(new File(outPath1));
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[CHUNK_SIZE];
int read = 0;
while ((read = zipStream.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
zipStream.closeEntry();
bufout.close();
fout.close();
}
}
zipStream.close();
Log.d("Unzip", "Unzipping complete. path : " );
} catch (Exception e) {
Log.e("TAG", e.getMessage());
}
return true;
}
If they realize where I failed in my code or I know otherwise. Please let me know. Thank you
I m getting this Error, when I upload to file with zipfile.
Error: Error creating zip file: java.io.FileNotFoundException: C:\fupload\qhT39xmU- (The system cannot find the file specified)
This is My Upload Method :
public String uploadToFts(UploadedFile filem, String fileType){
String fileFtsUrl = null;
String uploadUrl = fileDAO.findByUniqueProperty("name", "geturl").getPropValue();
String usr= fileDAO.findByUniqueProperty("name", "usr").getPropValue();
String pwd= fileDAO.findByUniqueProperty("name", "pwd").getPropValue();
String nameId= String.valueOf(passGen.create(1, 1, 8, 8, 0)) + "-";
try{
ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);
client.addFilter(new HTTPBasicAuthFilter(usr, pwd));
try {
FormDataMultiPart form = new FormDataMultiPart();
File file = new File("C:/fupload/"+nameId+"");
File thumbnail = new File("C:/fupload/"+nameId+"-tmb.jpg");
zipFile("C:/fupload/"+nameId+".zip", file, thumbnail);
File zipFile = new File("C:/fupload/"+nameId+".zip");
String urlParams = "nameId=" + nameId+ "&" +
"fileType="+fileType+"&" +
"fileName=" + zipFile.getName() + "&" +
"zipped=true";
form.bodyPart(new FileDataBodyPart("file", zipFile, MediaType.MULTIPART_FORM_DATA_TYPE));
WebResource resource = client.resource(uploadUrl + urlParams);
ClientResponse response = resource.type(MediaType.APPLICATION_OCTET_STREAM).put(ClientResponse.class, zipFile);
String respStr = response.getEntity(String.class);
if(respStr.contains("\"status\":0")){
System.out.println(respStr);
JSONObject obj = new JSONObject(respStr);
int jsonStatus = obj.getInt("status");
int jsonTxnId = obj.getInt("txnid");
String url = obj.getString("url");
fileFtsUrl = url;
} else {
addMessageToView(FacesMessage.SEVERITY_ERROR, "", "Can't uploading FTS"+respStr);
}
} catch (Exception e) {
e.printStackTrace();
}
return fileFtsUrl;
} catch (Exception e){
e.printStackTrace();
return fileFtsUrl;
}
}
ZipFile Method
public static void zipFile(String zipFile, File... srcFiles) {
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (int i = 0; i < srcFiles.length; i++) {
File srcFile = srcFiles[i];
FileInputStream fis = new FileInputStream(srcFile);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
} catch (IOException ioe) {
System.out.println("Error creating zip file: " + ioe);
}
}
I think you just need to create the file in zipFile(..), as it won't exist:
File file = new File(zipFile);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file, false);
Or maybe better to create it before and pass it to zipFile(file, ...), so you won't have to create it again just after the call. So pass a File instead of a String as with the other arguments.
Check with
System.out.println("C:/fupload/"+nameId+"")
System.out.println("C:/fupload/"+nameId+"-tmb.jpg")
Is exist in your system?
Make sure your path is must point file in your system
I've split a mp3 file of 10 MB size into 10 parts of 1 MB each in mp3 format on my Android device, each file plays successfully by the player but while reading the data of all the 10 files and writing it to a single file the total size of the new file is more than 17 MB and the file doesn't play itself. Following is the code:
CODE FOR FILE SPLIT :
File file = new File(Environment.getExternalStorageDirectory()
+ "/MusicFile.mp3");
try {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = null;
int size = 1048576; // 1 MB of data
byte buffer[] = new byte[size];
int count = 0;
int i = 0;
while (true) {
i = fis.read(buffer, 0, size);
if (i == -1) {
break;
}
File filename = getSplitFileName("split_" + count);
fos = new FileOutputStream(filename);
fos.write(buffer, 0, i);
++count;
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e2) {
e2.printStackTrace();
}
CODE FOR FILE JOIN :
File folder = new File(cacheDirSplit.getAbsolutePath());
File files[] = folder.listFiles();
BufferedReader bufReader = null;
BufferedWriter bufWriter = null;
if (files.length > 1) {
try {
File fileName = getJoinedFileName("NewMusicFile");
String data;
for (int i = 0; i < files.length; i++) {
long dataSize = 0;
bufReader = new BufferedReader(new FileReader(
files[i]));
bufWriter = new BufferedWriter(new FileWriter(
fileName, true));
while ((data = bufReader.readLine()) != null) {
bufWriter.write(data);
dataSize = dataSize + data.getBytes().length;
}
Log.i("TAG", "File : " + files[i] + "size ==> "
+ dataSize);
}
bufReader.close();
bufWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
What i do not understand is that while reading each file is read as 1.7MB as printed by the LOGCAT output but on the device when i check the splitted file is of 1MB only. Is there anything wrong with the code or is there some other thing I'm missing? Thanks in advance.
You cannot use readLine() on the content of an mp3 file. readLine() is for text files only. And if the ten were really playable and real mp3 files you had to strip the header first as Onur explained.
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();
I have this code to read bytes to another file.
But I'm not able to concatenate two mp3 files into one.
Am I missing something?
public static void main(String[] args) {
String strFileName = ("D:/Music/Assb/Love.mp3");
BufferedOutputStream bos = null;
try
{
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(strFileName));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);
String str = "D:/Music/Assembled/Heart001.mp3"
+ "D:/Music/Assembled/Heart002.mp3";
/*
* To write byte array to file use,
* public void write(byte[] b) method of BufferedOutputStream
* class.
*/
System.out.println("Writing byte array to file");
bos.write(str.getBytes());
System.out.println("File written");
It`s suck. Mp3 file starts with headers. For correct merging you have to skip first 32 bytes. Try this.
try {
FileInputStream fistream1 = new FileInputStream(_file_name);
File f = new File(new File(_file_name).getParent()+"/final.mp3");
if(!f.exists())
{
f.createNewFile();
}
FileOutputStream sistream = new FileOutputStream((new File(_file_name)).getParent()+"/final.mp3");
int temp;
int size = 0;
temp = fistream1.read();
while( temp != -1)
{
sistream.write(temp);
temp = fistream1.read();
};
fistream1.close();
FileInputStream fistream2 = new FileInputStream(temp_file);
fistream2.read(new byte[32],0,32);
temp = fistream2.read();
while( temp != -1)
{
sistream.write(temp);
temp = fistream2.read();
};
fistream2.close();
sistream.close();
} catch (IOException e) {
e.printStackTrace();
}
You need to do this in two steps
String str = "D:/Music/Assembled/Heart001.mp3";
>>> ADD code to open the file given by str <<<<
bos.write(strFile.getBytes());
>>> Add code to close the file
str = "D:/Music/Assembled/Heart002.mp3";
>>> ADD code to open the file given by str <<<<
bos.write(strFile.getBytes());
>>> Add code to close the file
And as you can see you need code to open the mp3 file to read it
What Are You Trying For...Actually..if You Want To Read 2 Files to Byte Stream the dont String str = "D:/Music/Assembled/Heart001.mp3"
+ "D:/Music/Assembled/Heart002.mp3";
make str1=D:/Music/Assembled/Heart001.mp3 and str2=D:/Music/Assembled/Heart002.mp3 and read str1,str2 seperately through bufferedoutputsream
This code will work well and merge audio of similar type with in seconds...
try {
InputStream in = new FileInputStream("C:\\a.mp3");//firstmp3
byte[] buffer = new byte[1 << 20]; // loads 1 MB of the file
OutputStream os = new FileOutputStream(new File("C:\\output.mp3", true);//output mp3
int count;
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
in = new FileInputStream("C:\\b.mp3");//second mp3
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}