Sub Directories under getCacheDir() - java

I'm trying to create sub directories in my apps cache folder but when trying to retrieve the files I'm getting nothing. I have some code below on how I created the sub directory and how I'm reading from it, maybe I'm just doing something wrong (well clearly I am lol) or maybe this isn't possible? (though I haven't seen anywhere that you can't). thank you all for any help!
creating the sub dir
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
File file2 = new File(file, each_filename);
Toast.makeText(getApplicationContext(), file2.toString(), Toast.LENGTH_SHORT).show();
stream = new FileOutputStream(file2);
stream.write(bytes);
reading from it
File file = new File(context.getCacheDir(), "SubDir");
File newFile = new File(file, filename);
Note note;
if (newFile.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = new FileInputStream(new File(file, filename));
ois = new ObjectInputStream(fis);
note = (Note) ois.readObject();
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return note;
}
I've also tried with this and nothing
String file = context.getCacheDir() + File.separator + "SubDir";

I don't see anywhere in the code you posted where you actually create the sub-directory. Here's some example code to save a file in a sub-directory, by calling mkdirs if the path doesn't yet exist (some parts here need to be wrapped in an appropriate try-catch for an IOException, but this should get you started).
File cachePath = new File(context.getCacheDir(), "SubDir");
String filename = "test.jpeg";
boolean errs = false;
if( !cachePath.exists() ) {
// mkdir would work here too if your path is 1-deep or
// you know all the parent directories will always exist
errs = !cachePath.mkdirs();
}
if(!errs) {
FileOutputStream fout = new FileOutputStream(cachePath + "/" + filename);
fout.write(bytes.toByteArray());
fout.flush();
fout.close();
}

You need to make your directory with mkdir.
In your code:
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
file.mkdir();
File file2 = new File(file, each_filename);

Related

File not created in Java (Eclipse)

So I've been doing like the simplest thing ever. Create a text file for a Java application. Just directly in the C directory:
File file = new File("C://function.txt");
System.out.println(file.exists());
The file never shows up though, I changed the slashes, changed the path, nothing. Could anyone help me out here?
There are many methods to create a new file with java : (You should firstly verify the permission to create a file in that folder c: )
String path = "C:"+File.separator"function.txt";
File f = new File(path);
f.mkdirs();
f.createNewFile();
__ or
try {
//What ever the file path is.
File f = new File("C:/function.txt");
FileOutputStream is = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("Line 1!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file function.txt");
}
After Java 7, you should use the new I/O API instead of the File class to create new files.
Here is an example:
Path path = Paths.get("C://function.txt");
try {
Files.createFile(path);
System.out.println(Files.exists(path));
} catch (IOException e) {
e.printStackTrace();
}
You are just creating a File object, not a file itself. So in-order to create new file you need use below command:
file .createNewFile();
This would create your file under C:\ drive. Maybe you can also check if it is already exsits and handle exception etc.
If the file is not exist you can create a new file like:
if(!file.exists()) {
try {
file.createNewFile();
System.out.println("Created a new File");
} catch (IOException e) {
e.printStackTrace();
}
}
The simplest way to do this:
String path = "C:"+File.separator+"function.txt";
File file = new File(path);
System.out.println(file.exists());
try this:
File file = new File("C://function.txt");
if (!file.isFile())
file.createNewFile();
Try this
File file = new File("C:/test.text");
f.createNewFile();

I keep getting java.io.FileNotFoundException with my zip extractor

Could anybody help me with my java zip extractor as stated in the title I keep getting java.io.FileNotFoundException on the folders with files in them
public void UnZip() {
try {
byte[] data = new byte[1000];
int byteRead;
BufferedOutputStream bout = null;
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
String filename = entry.getName();
File newfile = new File(Deobf2 + File.separator + filename);
System.out.println("file unzip : " + newfile.getAbsoluteFile());
new File(newfile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newfile);
int len;
while ((len = zin.read(data)) > 0) {
fos.write(data, 0, len);
}
fos.close();
entry = zin.getNextEntry();
}
zin.closeEntry();
zin.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
error log
http://pastebin.com/crMKaa37
values
static String tempDir = System.getProperty("java.io.tmpdir");
public static File Deobf = new File(tempDir + "Deobf");
public static String Deobf2 = Deobf.toString();
entire code paste
http://pastebin.com/1vTfABR1
I have copy pasted same code and it is working fine. I think u dont have administrator permission on C drive. login As Administrator and run . it will work.
Access Denied Exception will come when u don have administrator level of permission on C drive.
The problem is Your doing
String Deobf2 = Deobf.toString();//this does not give the location of the file
use
file.getAbsolutePath();
in your case Deobf.getAbsolutePath();
instead. Check http://www.mkyong.com/java/how-to-get-the-filepath-of-a-file-in-java/
if you want to get the path only till the parent directory check this How to get absolute path of directory of a file?
Problem fixed changed some code
for anyone whos wants a copy of the working zip extraction code here you go http://pastebin.com/bXL8pUSg
The variable Deobf2 in the output of the zip

Trying to create file without succes - file appears elsewhere?

I tried to create 3 empty files in my home directory, using this:
this.mainpath = System.getenv("HOME"+"/");
this.single = new File(mainpath + "sin.r");
this.complete = new File (mainpath + "com.r");
this.ward = new File (mainpath+"w.r");
I was unter the impression that this would give me the files desired. However, if I search my home directory, or any other directory, for this files, none of them exists. What am I doing wrong?
Edit: I just find out: I do get a file, but not in my home directory, but the path to it would be /home/myname/NetBeansProjects/myorojectname/nullsin.r.
However, I specifically wanted to create the file in my home!
Well, my code now reads:
this.mainpath = System.getenv("user.home");
this.mainpath = this.mainpath + "/";
this.single = new File(mainpath + "sin.r");
this.single.createNewFile();
System.out.println(this.single.getAbsolutePath());
this.complete = new File (mainpath + "comp.r");
this.complete.createNewFile();
this.ward = new File (mainpath+"w.r");
this.ward.createNewFile();
The "success" of this, however, is that I get an IOException at the first createNeWFile(): File not found.
as for my code how I tried to write sth into those file, there it is:
FileWriter writer1 = null;
FileWriter writer2 = null;
FileWriter writer3 = null;
try {
writer1 = new FileWriter(single);
writer2 = new FileWriter(complete);
writer3 = new FileWriter(ward);
writer1.write("x = cbind(1,2,3)");
writer2.write("x = cbind(1,2,3)");
writer3.write("x = cbind(1,2,3)");
writer1.flush();
writer2.flush();
writer3.flush();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
} finally {
try {
writer1.close();
writer2.close();
writer3.close();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
}
You need to use getProperty() instead
System.getProperty("user.home");
Also, the / should be appended after getting the directory path.
this.mainpath = System.getProperty("user.home");
this.single = new File(mainpath + "/sin.r");
this.complete = new File (mainpath + "/com.r");
this.ward = new File (mainpath+"/w.r");
You can call the "createNewFile"-method for each of the objects you've declared to actually create them.

java how to check if file exists and open it?

how to check if file exists and open it?
if(file is found)
{
FileInputStream file = new FileInputStream("file");
}
File.isFile will tell you that a file exists and is not a directory.
Note, that the file could be deleted between your check and your attempt to open it, and that method does not check that the current user has read permissions.
File f = new File("file");
if (f.isFile() && f.canRead()) {
try {
// Open the stream.
FileInputStream in = new FileInputStream(f);
// To read chars from it, use new InputStreamReader
// and specify the encoding.
try {
// Do something with in.
} finally {
in.close();
}
} catch (IOException ex) {
// Appropriate error handling here.
}
}
You need to create a File object first, then use its exists() method to check. That file object can then be passed into the FileInputStream constructor.
File file = new File("file");
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
}
You can find the exists method in the documentation:
File file = new File(yourPath);
if(file.exists())
FileInputStream file = new FileInputStream(file);

FileNotFoundException when trying to unzip an archive with java.util.zip.ZipFile

I have a silly problem i haven't been able to figure out. Can anyone help me?
My Code is as:
String zipname = "C:/1100.zip";
String output = "C:/1100";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
ZipFile zipFile = new ZipFile(zipname);
Enumeration<?> enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
System.out.println("Unzipping: " + zipEntry.getName());
bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
int size;
byte[] buffer = new byte[2048];
It doesn't create a folder but debugging shows all the contents being generated.
In Order to create a folder i used the code
if(!output.exists()){ output.mkdir();} // here i get an error saying filenotfoundexception
bos = new BufferedOutputStream(new FileOutputStream(new File(outPut)));
while ((size = bis.read(buffer)) != -1) {
bos.write(buffer, 0, size);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
bos.flush();
bos.close();
bis.close();
}
My zip file contains images: a.jpg b.jpg... and in the same hierarchy, I have abc.xml.
I need to extract the content as is in the zip file.
Any helps here.
There are a few problems with your code: Where is outPut declared? output is not a file but a string, so exists() and mkdir() do not exist. Start by declaring output like:
File output = new File("C:/1100");
Furthermore, outPut (with big P) is not declared. It be something like output + File.seprator + zipEntry.getName().
bos = new BufferedOutputStream(new FileOutputStream(output + File.seprator + zipEntry.getName()));
Note that you don't need to pass a File to FileOutputStream, as constructors show in the documentation.
At this point, your code should work if your Zip file does not contain directory. However, when opening the output stream, if zipEntry.getName() has a directory component (for instance somedir/filename.txt), opening the stream will result in a FileNotFoundException, as the parent directory of the file you try to create does not exist. If you want to be able to handle such zip files, you will find your answer in: How to unzip files recursively in Java?

Categories