I've been trying to save text to a file in the documents folder in internal storage to be accessed by file manager so i can read it, I've tried several methods including using a writer, but I can't seem to get it to work, I'm not trying to save to external storage, I don't have external storage, only internal, and that's where my documents folder is, so I'm assuming I don't have to bother with the permissions in manifest, I threw in the setReadable just in case but I still can't find it in the documents folder, this is where I'm currently at.
public void writeToFile(String string){
try {
File file = new File(Environment.DIRECTORY_DOCUMENTS, "myFile.txt");
file.setReadable(true);
FileOutputStream stream = new FileOutputStream(file);
stream.write(string.getBytes(string));
stream.flush();
stream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
File file = new File(Environment.DIRECTORY_DOCUMENTS, "myFile.txt");
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "myFile.txt");
Related
I have followed following approach to decompress a zip using apache commons compress:
But since I am using OutputStream & IOUtils.copy(ais, os); (code below) to unzip and copy file, the timestamp is not preserved. Is there another way to directly copy the file from the zip such that file timestamp can be preserved.
try (ArchiveInputStream ais =
asFactory.createArchiveInputStream(
new BufferedInputStream(
new FileInputStream(archive)))) {
System.out.println("Extracting!");
ArchiveEntry ae;
while ((ae = ais.getNextEntry()) != null) {
// check if file needs to be extracted {}
if(!extract())
continue;
if (ae.isDirectory()) {
File dir = new File(archive.getParentFile(), ae.getName());
dir.mkdirs();
continue;
}
File f = new File(archive.getParentFile(), ae.getName());
File parent = f.getParentFile();
parent.mkdirs();
try (OutputStream os = new FileOutputStream(f)) {
IOUtils.copy(ais, os);
os.close();
} catch (IOException innerIoe) {
...
}
}
ais.close();
if (!archive.delete()) {
System.out.printf("Could not remove archive %s%n",
archive.getName());
archive.deleteOnExit();
}
} catch (IOException ioe) {
...
}
EDIT: With the help of jbx's answer below, following change will make it work.
IOUtils.copy(ais, os);
os.close();
outFile.setLastModified(entry.getLastModifiedTime().toMillis()); // this line
You could set the lastModifiedTime file attribute using NIO. Do it to the file exactly after you write it (after you close it). The operating system would have marked its last modified time to the current time at that point.
https://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html
You will need to get the last modified time from the zip file, so maybe using NIO's
Zip Filesystem Provider` to browse and extract files from the archive would be better than your current approach (unless the APIs you are using provide you the same information).
https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html
My Code is:
String MyFile = "Riseone.dat";
String MyContent = "This is My file im writing\r\n";
File file;
FileOutputStream outputStream;
try {
file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS),MyFile);
outputStream = new FileOutputStream(file);
outputStream.write(MyContent.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
When I try this code MyFile creates in data/data/appfolder/files/Riseone.dat
but I want to create a file in DIRECTORY_DOWNLOADS.
also I want the file to write in append for next write action.
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), MyFile); corresponds to the file inside the Downloads directory of external shared storage. You might have seen older file in internal storage. Check it carefully.
If you want to append the data for next write, use append mode to create FileOutputStream using another constructor public FileOutputStream(File file, boolean append)
outputStream = new FileOutputStream(file, true);
Is there any way to create a folder structure inside of the local DCIM folder of an Android phone?
Android 5.1
I need to create the next folder structure.
DCIM/Camera/Notes
and create a file there.
I do the next:
File internalDcimDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
internalDcimDir = new File(internalDcimDir, "Camera");
internalDcimDir = new File(internalDcimDir, "Notes");
internalDcimDir.mkDirs();
And when I try to create a file no exceptions occure
File file = new File(internalDcimDir, noteFileName);
And when I write something..
FileOutputStream outputStream = null;
try {
OutputStream fo = new FileOutputStream(file);
fo.write(content.getBytes());
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
it occures that there is no file and even dirs created.
May be I am doing something wrong. What can it be?
Couldn't find too much about how to read a file that isn't somewhere on the SD card or storage, but rather right there in the android project directory.
I keep getting a FileNotFoundException. This is how I declare the file,
File SPPolicy = new File("SHPR_policy");
I've gotten the same error when putting it in the src/ directory, the src/[[package]]/ directory and the main project directory, and I get this error:
java.io.FileNotFoundException: /SHPR_policy: open failed: ENOENT (No such file or directory)
Is there a certain place I have to put this file? Is it because my file doesn't have an extension (I noticed the "/" before SHPR_policy but I didn't think it would be a problem because Eclipse let me create a file without an extension)?
Save the file in raw folder and try the below code.
try
{
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.test);
byte[] b = new byte[in_s.available()];
in_s.read(b);
txtHelp.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
txtHelp.setText("errr.");
}
Use these piece of code to check if the file was already created:
File f;
f=new File("myfile");
if(!f.exists()){
f.createNewFile();
}
Also, if you want to allocate your file in the external directory you can use these code:
File newxmlfile = new File( Environment.getExternalStorageDirectory() + "/new.xml");
XmlSerializer serializer = Xml.newSerializer();
try {
newxmlfile.createNewFile();
} catch (Exception e) {
Log.e("IOException", "exception in createNewFile() method", e);
}
And, did you added the permission in the manifest to be able to manipulate files?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should place the file in the assets folder and use this:
InputStream ims = getAssets().open("SHPR_policy");
I am making a program that would save the inputted word in an EditText to a textfile in sd card. However, there is something wrong about mounting sd card in my tablet so im thinking of saving the text file to internal storage instead. Can anyone please help me how to switch this to internal storage? any comment would be greatly appreciated.thank you.
Here's my code:
public void writeToSDFile() {
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
File dir = new File (root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "wordlist.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(stringword);
pw.append(stringword);
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found.");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}//end writeToSDFile
This should be able to help you: http://developer.android.com/guide/topics/data/data-storage.html
Since external storage is removable, you should not presume that it exists all the time. Hence before doing any io operation, check the storage state.
About your question to internal storage, There are two ways:
1. In application storage (app cache) - refer: Environment.getDataDirectory()
2. In common Data directory - refer: Context.getCacheDir().
Hope this helps.