I've created this code to save a pdf file in sd card, but I want to change the directory that has the saved files, from /sdcard/, to /sdcard/MYDIR/
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/yes.pdf");
To create a directory in Java, use mkdir() or mkdirs() on File.
To correctly create a directory or file on external storage on Android, do not hard-code /sdcard, largely because it is the wrong value on most Android devices. Use Environment.getExternalStorageDirectory() to access the root of external storage.
File dir=new File(Environment.getExternalStorageDirectory(), "MYDIR");
dir.mkdir();
OutputStream output=new FileOutputStream(new File(dir, "yes.pdf"));
The class you need is File. There you have methods like mkdirs() that creates the necessary directories.
You should make sure that you don't use hard coded paths in your application. On some devices your "/sdcard/" will fail. Check the class Environment and use the getExternalStorageDirectory() to get the path of the sd card.
Related
I must use an existing method: method.invoke(myClassLoader, myFile.toURI().toURL()); where myFile is an instance of File and I need to create it from a byte[] without saving the file on the disk, is this possible?
This is what I tried but it creates a file on the disk and writes it:
byte[] bytes = ...;
File tempFile = File.createTempFile("prefix", "suffix");
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(bytes);
method.invoke(myClassLoader, tempFile.toURI().toURL());
The parameter of the invoked method is URL. You can use Jimfs (An in-memory file system for Java 7+) to create a file emulation in memory and get its URL (path.toUri().toURL()).
I am creating an application were i am reading the content from a file present in internal storage and displaying in the application.
I am creating a file on the desktop and transferring that file to the mobile using usb cable.If sdcard is present the file will be stored in sdcard and for accessing the file i found the following code and it worked for me.
File path = Environment.getExternalStorageDirectory();
/storage/sdcard0/Filename.txt is the path which i am getting when i run the above code.If file is present in sdcard it is returning true else false.
If sdcard is not present and when i transfer the file from desktop to mobile it gets stored in internal storage.in this case how do i access my file.
In some cases i have come to know that sdcard0 is internal storage and not the external storage.
Which is the best way to find the file existence in internal storage of the mobile and not apps internal storage. please help.
Thanks in advance
To find out the path for your app's internal storage you can use the following commands:
Context context = getApplicationContext();
or
Context context = getApplication();
String dir = context.getFilesDir().getAbsolutePath();
String dir = context.getFilesDir().getPath();
getFilesDir() returns a File object that you can get the path from there. Then you can use that path to transfer your file. Also read below.
See here on how to write a file to internal storage and here on getting the path for internal storage.
The following code gives you the path for the your file in internal storage and then you can open it:
String yourFilePath = context.getFilesDir() + "/" + "filename";
File yourFile = new File( yourFilePath );
You can also use the following approach explained in here
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = context.openFileInput(filename);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fileContent.append(new String(buffer));
}
The above solution opens input stream to the file name provided using the context that gives the location where the files are stored in internal storage. In the while loop it reads from the input stream (up to size of buffer) every iterator and adds the read data to StringBuilder instance. The loop terminates when the length of the read data from input stream is -1.
If the file is not found, FileNotFoundException will be throw by openFileInput(filename) method.
I'm trying to download (and later extract) a zip file from my dropbox account using this code
URL url = new URL("-");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
try (InputStream stream = con.getInputStream()) {
Files.copy(stream, Paths.get(parent.getAbsolutePath() + File.separator + "zippedCache.zip"));
}
The file I'm trying to download is a folder with another folder in it (empty). When I attempt to open the zipped folder, I get something along the lines of "cannot open the folder the compressed zipped folder is invalid" (translated using Google translator). When I unzip it, it's empty.
Can anyone explain what the problem here is?
Edit: Also, the zip folder is empty when I download it using Java, however downloading it normally through a web browser works fine.
Please verify your code again using a HttpURLConnection. This should work out.
For using Https you would need something like urlConnection.setSSLSocketFactory or similar.
You should try to read the InputStream in parts into a byte array and write into a FileOutputStream. It's simpler I think.
Example:
InputStream stream = con.getInputStream();
byte[] buffer = new byte[4096];
FileOutputStream out = new FileOutputStream("anything.zip");
while (stream.read(buffer) != -1) {
out.write(buffer);
}
I have the following code that writes a text file in a zip:
FileOutputStream fOut = new FileOutputStream(fullFilename, false);
BufferedOutputStream bOut = new BufferedOutputStream(fOut);
ZipOutputStream zOut = new ZipOutputStream(bOut);
zOut.putNextEntry(new ZipEntry("aFile1.txt"));
//Do some processing and write to zOut...
zOut.write(...);
(...)
zOut.closeEntry();
zOut.close();
//Etc (close all resources)
I would need to change the filename of the zipEntry after it has been written (as its name will depend on its content written).
Also, it is not an option to write in a buffer and write to file only when final filename is known (because file size is potentially very large: not enough memory).
Any advice on how to do this would be greatly appreciated!
Thanks,
Thomas
It is a missing functionality, which could have been simple, as the entries themselves are not compressed.
The easiest way, requiring a rewrite though, is the zip FileSystem: since java 7 you may use a zip file as a virtual file system: writing, renaming and moving files in them. An example. You copy a file from the normal file system into the zip file system, and later rename the file in the zip.
// Create the zip file:
URI zipURI = URI.create("jar:file:" + fullFilename); // "jar:file:/.../... .zip"
Map<String, Object> env = new HashMap<>();
env.put("create", "true");
FileSystem zipFS = FileSystems.newFileSystem(zipURI, env, null);
// Write to aFile1.txt:
Path pathInZipfile = zipFS.getPath("/aFile1.txt");
BufferedWriter out = Files.newBufferedWriter(pathInZipfile,
StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
out.write("Press any key, except both shift keys\n");
out.close();
// Rename file:
Path pathInZipfile2 = zipFS.getPath("/aFile2.txt");
Files.move(pathInZipfile, pathInZipfile2);
zipFS.close();
In principle you could also keep your old code - without renaming. And use a zip file system just for renaming.
How about saving the contents of aFile1.txt to a temporary file on disk, renaming it, and then creating the zip file afterwards? The last step can then be deleting the file you created on disk.
I need to be able to access a file stored in a compiled jar file. I have figured out how to add the file to the project, but how would I reference it in the code? How might I copy a file from the jar file to a location on the user's hard drive? I know there are dozens of ways to access a file (FileInputStream, FileReader, ect.), but I don't know how to look inside itself.
You could use something like this:
InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileFromJarFile);
If foo.txt was in the root of your JAR file, you'd use:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("foo.txt");
assumes the class is in the same JAR file as the resource, I believe.
You can use getResource() to obtain a URL for a file on the classpath, or getResourceAsStream() to get an InputStream instead.
For example:
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("foo.txt")));
You could read the contents of a JAR file using the JarFile class.
Here's an example of how you could get a specific file from a JAR file and extract it:
JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[input.available()];
for (int i = 0; i != -1; i = input.read(buffer)) {
output.write(buffer, 0, i);
}
} finally {
jar.close();
input.close();
output.close();
}
Just wanted to add that if we want to access file inside Jar that is located at the following path(only examples as resources loading is OS independent):
Windows:
c:\your-jar-file.jar\dir1\dir2\dir3\foo.txt
Linux:
/home/your-jar-file.jar/dir1/dir2/dir3/foo.txt
Will need to use following code(pay attention that there is NO "/"(forward-slash) character in the beginning of the path):
InputStream is = this.getClass().getClassLoader().getResourceAsStream("dir1/dir2/dir3/foo.txt");
Look at the JarFile class. Everything you need to get the InputStream of a specific entry in the jar file is there.