getResourceAsStream() is not working in built product - java

I am trying to copy the image files from resource folder to local system with using following code.
InputStream inStream = null;
OutputStream outStream = null;
File bfile = new File(directoryPath + "/icons/" + outputFileName);
inStream = MyClass.class.getClassLoader().getResourceAsStream("/images/" + imgFileName);
try {
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
if (inStream != null && outStream != null) {
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
This code works absolutely fine when I run through eclipse. But when i build the product, icons are not getting copied to local system.
I also tried
inStream = MyClass.class.getResourceAsStream("/images/" + imgFileName);
but no luck.
Any thoughts!

For opening an input stream consider using FileLocator API:
FileInputStream is = null;
FileOutputStream fo = null;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
File bfile = new File(directoryPath + "/icons/" + outputFileName);
try {
is = FileLocator.openStream(Activator.getDefault().getBundle(), new Path("/images/" + imgFileName), false);
inputChannel = is.getChannel();
fo = new FileOutputStream(bfile);
outputChannel = fo.getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
// close everything in finally
}
Also, please note, that it is better to close streams and channels in the finally block

Related

How to copy content from a zip to an Android directory?

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

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();
}
}

FileInputStream for a raw file

I have a raw file in res/raw named "pack.dat".
I can open an InputStream with the following code:
InputStream fis = null;
try {
fis = context.getResources().openRawResource(R.raw.pack);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String nextLine;
int i = 0, j = 0;
while ((nextLine = br.readLine()) != null) {
if (j == 5) {
j = 0;
i++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
This is working, I can read from that file.
But unfortunately I need a FileInputStream. When I do this:
FileInputStream fs = null;
Uri url = Uri.parse("android.resource://" +
context.getPackageName() + "/" + R.raw.pack);
File file = new File(url.toString());
try {
fs = new FileInputStream(file);
fs.getChannel().position(0);
fs.read(bDatensatz, 0, indexlaenge);
} catch (Exception e) {
e.printStackTrace();
}
I get a "file not found" at
fs = new FileInputStream(file);
context.getResources().openRawResource(R.raw.pack) in the first example returns an InputStream.
What can I use to get a FileInputStream instead?
copied from another thread! may be this should help you
FileInputStream fis;
fis = openFileInput("test.txt");
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
int n = 0;
while ((n = fis.read(buffer)) != -1)
{
fileContent.append(new String(buffer, 0, n));
}
But unfortunately I need a FileInputStream
Why?
I get a "file not found" at fs = new FileInputStream(file);
That is because you are trying to open something that is not a file.
What can I use to get a FileInputStream instead?
You would need to copy the resource to a local file (e.g., using openFileOutput() and Java I/O). Then, you can open the local file (e.g., using openFileInput()) and get a FileInputStream.
Or, just use the InputStream, fixing whatever code that you are using that is expecting a FileInputStream.

multidownload using java servlets

I want to download multiple files in single zip file using java servlet. I successfully downloaded the zip file containing multiple files (in my web page). but the problem is that files are also downloaded in my server(for ex in my jboss bin folder).
Code:
public void createZipFile(String fileNames,HttpServletResponse response,HttpServletRequest request) {
try {
ZipOutputStream outStream1 = null;
ServletOutputStream outStream=null;
FileInputStream inStream =null;
FileOutputStream fos=null;
InputStream inputStream =null;
int bytesRead = 0;
String zipFileName = "zipFileName.zip";
response.setHeader("Content-Disposition", "attachment;filename=\""+zipFileName+"\"");
response.setHeader("Pragma", "private");
response.addHeader("Cache-Control", "no-transform, max-age=0");
response.setHeader("Accept-Ranges", "bytes");
response.setContentType("application/zip");
//fileNames contains multiple file name.so i want to split and get each file
String[] fileName = fileNames.split(",");
byte[] buffer = new byte[1024];
outStream1 = new ZipOutputStream(new FileOutputStream(zipFileName));
for(int i = 0; i < fileName.length; i++) {
String filePath=audioFile.getAllFiles(fileName[i], Integer.parseInt(userId));
inputStream = new URL("************************server File location***************************").openStream();
String fileNaming = fileName[i];
String[] tempFile = fileNaming.split("\\.");
String tempFileExt=tempFile[1];
String temporaryFile=tempFile[0]+"."+tempFileExt;
fos = new FileOutputStream(temporaryFile);//here is the problem(temporary file created in my server -bin folder.but i dont want this to create)
int length = -1;
while ((length = inputStream.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
inStream = new FileInputStream(fileName[i]);
outStream1.putNextEntry(new ZipEntry(fileName[i]));
fos.close();
inputStream.close();
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream1.write(buffer, 0, bytesRead);
}
}
inStream.close();
outStream1.closeEntry();
outStream1.close();
int bytesRead1 = 0;
byte[] buff = new byte[1024];
ByteArrayOutputStream bao = new ByteArrayOutputStream();
FileInputStream inStream1 =new FileInputStream(zipFileName);
while ((bytesRead1 = inStream1.read(buff)) != -1)
{
bao.write(buff, 0, bytesRead1);
}
byte[] videoBytes = bao.toByteArray();
response.setContentLength(videoBytes.length);
outStream = response.getOutputStream();
outStream.write(videoBytes);
outStream.flush();
outStream.close();
bao.close();
response.flushBuffer();
} catch (Exception ex) {
ex.printStackTrace();
}
}
For whatever reason, you're copying the files twice. Once, to the file system via inputStream and fos, and the second time to the ZipFile, via inStream and outStream1.
Seems like you can simply remove all of the code related to inputStream and fos, and you won't create the files on your filesystem.

read the file inside a jar but then can not delete it

my thread will read the class data from a jar file, another thread will modify or delete the jar file. the order is read first then delete, but it didn't work, seem that cann't release the resource after reading, how could I reach out?
InputStream is = null;
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try {
URL res = new URL(**file**);
is = res.openStream();
bis = new BufferedInputStream(is);
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024 * 10];
int readBytes;
while ((readBytes = bis.read(bytes)) != -1) {
baos.write(bytes, 0, readBytes);
}
byte[] b = baos.toByteArray();
baos.close();
bis.close();
is.close();
return b;
} catch (Exception ex) {
throw ex;
}
the parameter "file" is a String like this "jar:file:///C:/Users/HJ16748/Desktop/test.jar!/com/services/plugin/test/Test.class"
Add a finally to your try catch block and close the resources there. Let two threads name be Read and Modify.
Inside Modify thread before deleting or modifying jar add line like this.
try{
System.out.println("Waiting for read to finish");
read.thread.join();
}catch(InterruptedException e){
System.out.println("not able to join");//oops catch
}
//codes to delete or modify jar
thread called with read is the Thread object
ZipFile zf = new ZipFile(entry);
file = file.replaceAll("\\\\", "/");
ZipEntry zipEntry = zf.getEntry(file);
BufferedInputStream bis = new BufferedInputStream(zf.getInputStream(zipEntry));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024 * 10];
int readBytes;
while ((readBytes = bis.read(bytes)) != -1) {
baos.write(bytes, 0, readBytes);
}
b = baos.toByteArray();
baos.close();
bis.close();
zf.close();

Categories

Resources