FileInputStream for a raw file - java

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.

Related

How to release a file in Java GUI without closing

I've created a pretty simple Java GUI to browse/load a zip file on Windows platform to begin unzipping and then do some file checking.
Everything works fine except that I have to close the GUI window in order to delete the zip file that has been opened in the GUI.In my finally block of the unzipping method, I've tried adding the following:
public static String unZip(String path)
{
int count = -1;
String savepath = "";
File file = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
savepath = path.substring(0, path.lastIndexOf("\\")) + File.separator; //File saving directory
new File(savepath).mkdir(); //create the saving directory
ZipFile zipFile = null;
String topLevelDirName="";
try
{
zipFile = new ZipFile(path,Charset.forName("gbk")); //Encoding
Enumeration<?> entries = zipFile.entries();
int levelCount=0;
while(entries.hasMoreElements())
{
byte buf[] = new byte[buffer];
ZipEntry entry = (ZipEntry)entries.nextElement();
String filename = entry.getName();
boolean ismkdir = false;
if(filename.lastIndexOf("/") != -1){ //To check if there is a directory
ismkdir = true;
}
filename = savepath + filename;
if(entry.isDirectory()){ //If it is a directory
levelCount++;
file = new File(filename);
file.mkdirs();
if(levelCount==1)
topLevelDirName = filename;
continue;
}
file = new File(filename);
if(!file.exists()){
if(ismkdir){
new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs();
}
}
file.createNewFile(); //Create the file
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, buffer);
while((count = is.read(buf)) > -1)
{
bos.write(buf, 0, count);
}
bos.flush();
bos.close();
fos.close();
is.close();
}
zipFile.close();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
try{
if(bos != null){
bos.close();
}
if(fos != null) {
fos.close();
}
if(is != null){
is.close();
}
if(zipFile != null){
zipFile.close();
}
}catch(Exception e) {
e.printStackTrace();
}
return topLevelDirName;
}
}
However, I am still not able to delete the zip unless explicitly close the GUI.
Wonder if there is anything to do with the Windows file handle?Thanks in advance.
Java 8 introduced the try-with-resources Statement to make this kind of situation simpler and cleaner.
One of the issues you have is, if any one of the attempts to close the many resources you have open fails, then none of the others will be closed
public static String unZip(String path) throws IOException {
int count = -1;
File sourceFile = new File(path);
String name = sourceFile.getName();
name = name.substring(0, name.lastIndexOf(".zip"));
File sourcePath = new File(sourceFile.getParent(), name);
System.out.println("SavePath = " + sourcePath);
if (!sourcePath.exists() && !sourcePath.mkdirs()) {
throw new IOException("Could not create directory " + sourcePath);
}
String topLevelDirName = "";
try (ZipFile zipFile = new ZipFile(sourceFile)) {
Enumeration<?> entries = zipFile.entries();
int levelCount = 0;
byte buf[] = new byte[1024];
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String filename = entry.getName();
File file = new File(sourcePath, filename);
if (entry.isDirectory()) { //If it is a directory
levelCount++;
System.out.println("Make directory " + file);
if (!file.exists() && !file.mkdirs()) {
throw new IOException("Could not create directory " + filename);
}
} else {
System.out.println("Extract to " + file);
try (InputStream is = zipFile.getInputStream(entry);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
while ((count = is.read(buf)) > -1) {
bos.write(buf, 0, count);
}
}
}
}
}
return topLevelDirName;
}
I've update the code slightly to try and make it a little cleaner and simpler and to take advantage of the available APIs

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

getResourceAsStream() is not working in built product

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

Joining two mp3 files into one

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

Java: unzipping is significantly slower than zipping

I have some code that zips up a file sends it over the network and then unzips it on the other end. I'm still testing the code and the source and the destination are the same. Zipping up the file takes on the order of a minute. Unzipping the file takes on the order of an hour. I'm think there must be a flaw in my code to have such a large difference. Here's the code to unzip:
public String uncompressLocalZip(String filename,String strUUID,ParentEntry pe,boolean bControlFileProgress) {
final int BUFFER = 2048;
BufferedOutputStream out = null;
ZipInputStream zis = null;
try {
FileInputStream fis = new FileInputStream(Constants.conf.getFileDirectory() + Constants.PATH_SEPARATOR + strUUID + Constants.PATH_SEPARATOR + filename);
zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
long totallength = 0;
long size = 0;
if (pe !=null)
size = pe.getSize();
while((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " +entry);
int count;
byte data[] = new byte[BUFFER];
// write the files to the disk
File fileOutput = new File(Constants.conf.getFileDirectory() + Constants.PATH_SEPARATOR + strUUID + Constants.PATH_SEPARATOR + Constants.conf.getUncompressFolderName() + Constants.PATH_SEPARATOR + entry.getName());
new File(fileOutput.getParent()).mkdirs();
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(fileOutput));
out = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
totallength += count;
}
out.flush();
}
}
catch(Exception e) {
e.printStackTrace();
return("FAILED");
}
finally {
try {if ( out!= null) out.close();} catch (IOException ioe) {}
try {if ( zis!= null) zis.close();} catch (IOException ioe) {}
}
return("SUCCESS");
}
Here's the code to zip:
public void createLocalZip(String filename,ProcessEntry pe) {
ZipOutputStream out=null;
try {
File fileOutput = new File (filename);
out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(fileOutput)));
long totallength=0;
long size = pe.getParentEntry().getSize();
String strStartDirectory;
if (pe.getParentEntry().isDirectory())
strStartDirectory=pe.getParentEntry().getUrl();
else
strStartDirectory=pe.getParentEntry().getFolder();
for (int i=0;i<pe.getParentEntry().tableModel3.getRowCount();i++) {
FileEntry fe = pe.getParentEntry().tableModel3.getFileEntry(i);
File fileInput = new File (fe.getUrl());
FileInputStream input = new FileInputStream(fileInput);
BufferedInputStream in = new BufferedInputStream(input);
String strRelativeDir = fe.getUrl().substring(strStartDirectory.length()+1,fe.getUrl().length());
ZipEntry entry = new ZipEntry(strRelativeDir);
out.putNextEntry(entry);
byte[] bbuf = new byte[2048];
int length=0;
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
out.write(bbuf,0,length);
totallength += length;
pe.setProgress((int) (totallength*100/size));
}
in.close();
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
try {if (out!=null) out.close();} catch(IOException ioe){}
}
}
Update: The compression ratio for this particular test is about 90% (1.2GB down to about 100MB). So I suppose it could be the extra writing to disk for unzipping vs. zipping, although I would expect close to a 10X differential vs 60X.
don't double wrap your OutputStream with BufferedOutputStream (you only need 1 BufferedOutputStream wrapper), and close it after you are done writing to it.
also, ZipEntrys can be directories, so check that and handle accordingly.
I have no really big file to test your code, so I can only guess.
You say your uncompressed zip size is more than 1 GB. This could be more than fits in your memory, and if something forces the VM to fit everything in memory, it will have to swap. Observe your program with a profiler.
Make sure your close each FileOutputStream after writing to it. (You create lots of them, and only close the last one.)
I'm not sure about the ZipInputStream implementation (maybe it forces your BufferedStream to buffer much of data). You could try ZipFile instead (which allows random access, basically).
Consider using a specialized library to do the zipping/unzipping. http://sevenzipjbind.sourceforge.net/ might help.

Categories

Resources