I'm trying to create a directory hierarchy and then copy a file from my assets into the newly created directory. I've used the code samples offered here on stackoverflow but I'm not getting anywhere. Essentially my code goes like this:
InputStream in = getAssets.open(mydb.sqlite);
File dir = new File("/data/data/my.package/databases/");
dir.mkdirs();
out = new FileOutputStream("/data/data/my.package/databases/mydb.sqlite");
while ((len = in.read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
out.flush();
out.close();
in.close
This is all done within the main activity on first launch and of course should only be done once. Before the code runs, the only directory that exists is /data/. Yes, it is a database file but that shouldn't matter at this point since I'm just copying the file and haven't yet tried to access it with the database code.
The code doesn't throw any exceptions, and dir.mkdirs() returns true. Regardless, the directories are not created and the file is not copied. I have added the permissions line for WRITE_EXTERNAL_STORAGE to my manifest as has been suggested in several places, FWIW. I can step through the code and everything appears to be fine. But of course it's not.
What do I need to be looking for here? File permissions problems? Why does the code think everything is there (ie, when it gets to the copy code, it doesn't throw FileNotFoundException) but in reality there's nothing on the file system?
Edit: Here's what I've learned. getDir() creates the directory in /data/data/my.package/app_*. Not sure why it uses this prefix on the directory name. This won't work if you need to put something in a standard location such as databases/ or files/.
Use openFileOutput instead as /data/data is internal storage and you should only use the Android APIs to get a file handle there. See: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Edit:
/data/data/my.package is handled by openFileOutput/getDir so you would create your directory with getDir('databases',MODE_PRIVATE) and create your file there.
Edit2:
From getDir documentation:
You can use the returned File object to create and access files in this directory.
Related
I have been searching for a way to get a file object from a file, in the resources folder. I have read a lot of similar questions on this website but non fix my problem exactly.
Link already referred to
how-to-get-a-path-to-a-resource-in-a-java-jar-file
that got really close to answering my question:
String path = this.getClass().getClassLoader().getResource(<resourceFileName>)
.toExternalForm()
I am trying to have a resource file that I can write data into and then bring that file object to another part of my program, I know I can technically create a temp file that, I then write data into then pass it into a part of my program, the problem with this approach is that I think it can take a lot of system recourses, my program will need to create a lot of these temp files.
Is there any way, I can reuse one file in the resource folder? all I need is to get it's path (and it needs to work in a jar).I have tried this snipper of code i created for testing, i don't really know why it returns false, because in the ide it returns true.
public File getFile(String fileName) throws FileNotFoundException {
//Getting file from the resources folder
ClassLoader classLoader = getClass().getClassLoader();
URL fileUrl = classLoader.getResource(fileName);
if (fileUrl == null)
throw new FileNotFoundException("Cannot find file " + fileName);
System.out.println("before: " + fileUrl.toExternalForm());
final String result = fileUrl.toExternalForm()
.replace("jar:" , "")
.replace("file:" , "");
System.out.println("after: " + result);
return new File(result);
}
Output:
before: jar:file:/C:/Users/%myuser%/Downloads/Untitlecd.jar!/Recording.wav
after: /C:/Users/%myuser%/Downloads/Untitlecd.jar!/Recording.wav
false
i have been searching for a way to get a file object from a file in the resources folder.
This is flat out impossible. The resources folder is going to end up jarred into your distribution, and you can't edit jar files, they are read only (or at least, you should consider them so. Non-idiotic deployments will generally mark their own code files (which includes those jars) as read-only to the running process. Even if not, editing jar files is extremely heavy and not something you want to do. Even if you do, on windows, open files can't be edited/replaced like this without significant headaches).
The 'resources' folder simply isn't designed for files that are meant to be modified.
The usual strategy is to make a directory someplace (for example, the user's home dir, accessing via System.getProperty("user.home"), and then make/edit files within that dir. If you wish, you can put templates in your resources folder and use those to 'initialize' that dir hanging off the user's home dir with a skeleton version.
If you have a few ten thousand files to make, whatever process needs this needs to be adjusted to not need this. For example, by using a database (H2, perhaps, if you want to ship it with your java app and have it be as low impact as possible).
First I'm writing the excel file in a temporary location then I'm downloading it from that location. Here is the code:
Here I'm writing excel into some temporary location and returning the location of that file:
public String parseExcel(Map<String, List<String>> data) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("Sheet1");
.
.
.
var tmplocation = File.createTempFile("SampleTemplate", ".xlsx");
FileOutputStream fileOut = new FileOutputStream(tmplocation);
workbook.write(fileOut);
fileOut.close();
return tmplocation.getPath();
}
And here I'm downloading that file from that location:
try {
filePath = parseExcel(data);
file = new File(filePath);
return Cors.add(request, Response.ok(file).header("Content-Disposition",
"attachment;filename=\"SampleTemplate.xlsx\"").header("Content-Length ", file.length())).allowAllOrigins().auth().build();
} catch() {
.
.
.
}
To delete the temporary file I added finally block and in finally block I'm getting the file, but it didn't worked. It said FileNotFound Exception
How can I delete this temporary file after the successful download of the file?
The deleteIfExists() method of java.nio.file.Files can help you.
Deletes a file if it exists.
As with the delete(Path) method, an implementation may need to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link, then the symbolic link itself, not the final target of the link, is deleted.
If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
You may also wish to use createTempFile() to create your file.
For reference:
Java better way to delete file if exists
Java Tutorials - Deleting a File or Directory
You want to delete a file? You might think of file.delete ();.
You can find that it actually exists by reading the documentation for the File class and scanning the list of methods. In doing so, you will see things that you will remember later on, so it is a great way to expand knowledge.
Documentation is useful.
If you use an IDE like Eclipse, you can get a context-sensitive menu of suggestions, usually a list of possible methods you might use.
I'm having trouble uploading an image in my website. Sometimes, it uploads. But sometimes it also says can’t create cache file. How do I fix it?
Here's my code:
File file = new File(imagePath);
BufferedImage bi;
try{
bi = ImageIO.read(file);
}catch(javax.imageio.IIOException e){
if(request.getParameter("fi") != null){
file = new File(context.getInitParameter("ImgPath") + "placeholder/150x80.png");
}else if (request.getParameter("li") != null){
file = new File(context.getInitParameter("ImgPath") + "placeholder/150x80.png");
}
bi = ImageIO.read(file);
}
OutputStream outImg = response.getOutputStream();
File cacheDir = new File(context.getInitParameter("ImgPath") + "cache");
try {
ImageIO.setCacheDirectory(cacheDir);
ImageIO.write(bi, "png", outImg);
} catch (Exception ex) {
}
outImg.close();
Problem: Your tomcat installation is failed to create temp folder on startup or temp folder is not writable.
Solution: Make sure temp folder exists under \temp and it is writable.
You can create it manually.
Or
You can override default temp folder location of Tomcat by setting the value for CATALINA_TMPDIR environment variable in catalina.bat (windows) or catalina.sh (linux).
# CATALINA_TMPDIR (Optional) Directory path location of temporary directory
# the JVM should use (java.io.tmpdir). Defaults to
# $CATALINA_BASE/temp.
In which security context are your code in? In some implementation of 'multiple bundle on single virtual machine' framework, there can exist two types of bundles, one has permission to write temp folder, and the other does not. If the former would access ImageIO package first, ImageIO package determined that it would have permission to write temp folder, and trying to use it all of subsequent calls, but, in such frameworks, the latter can call ImageIO as well, and it will fail, since that bundle does not have access to the temp file. The behavior would change either the former would access first or vice versa, and if the latter would call ImageIO first, it won't ever use cache directory for that virtual machine instance and you don't see any troubles.
If your code does not have access to the cache directory and someone which has access to there calls ImageIO first, your code will fail.
And, it seems that your code would call ImageIO.setCacheDirectory() with your local data folder. In such frameworks, there are many cases that other bundles running on the same virtual machine would not have access to the local folder of your bundle. If so, they would have to throw IOException, if your setCacheDirectory() call was successful and you have given the directory only your code can access.
If your code successfully set the cache directory to your local data folder which other bundles cannot access to, your code might work fine, but other bundles would fail when trying to use ImageIO.
I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.
I have eclipse plugin jface application.
A thread writes file via BufferedWriter.
After writing is done I close the buffer after that I try to rename the file.
But sometimes file is not renamed!
I tried to add some Thread.Sleep(BIG_NUMBER) between couple of retries this didn't help.
It looks like the file getting some kind of lock. (when I kill the jvm I can rename the file).
Is there something I can do?
OS: Windows XP, windows 7
JAVA version: 1.5
File.RenameTo() is platform dependent and relies on a few conditions to be met in order to succesfully rename a file, a better alternative is using
Path source = currentFile.toPath();
try {
Files.move(source, source.resolveSibling(formattedName));
} catch (IOException e) {
e.printStackTrace();
}
Read more here.
From the javadocs:
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
Note that the Files class defines the move method to move or rename a file in a platform independent manner.
For the File.renameTo() to work,The file will need to be somehow writable by external applications.
You can also do something like below:
File o=new File("oldFile.txt");
File n=new File("newFile.txt");
n.delete();
o.renameTo(n);
n.delete() : We need to delete the file(new.txt) if exists.
o.rename(n) : so that the file(old.txt) is renamed as new.txt
How to find out why renameTo() failed?
Reliable File.renameTo() alternative on Windows?
http://www.bigsoft.co.uk/blog/index.php/2010/02/02/file-renameto-always-fails-on-windows
We have had issues under Windows 7 with UAC and unexpected file permissions. File#canWrite will return true even though any attempts to perform file I/O will fail.
Make sure the file you are trying to rename actually exists
Make sure that the location you are attempting to write the file (or rename the file) to is accessible. We write a simple text file to the location, check to see if it exists and that it's contents is correct (we're paranoid) before we attempt any further I/O.
This is working fine for me. Rename is done using two steps but don't forget to set permissions in manifest.xml with:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
public boolean RenameFile(String from, String to) {
to.replace(" ", ""); // clear all spaces within file name
File oldfile = new File(from);
File newfile = new File(to);
File tempfile = new File(to + ".tmp"); // add extension .tmp
oldfile.renameTo(tempfile);
return (tempfile.renameTo(newfile));
}