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.
Related
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");
Can someone please tell me if what I'm doing is correct?
File directoryToStore;
directoryToStore = getBaseContext().getExternalFilesDir("MyFiles");
Bitmap b = ThumbnailUtils.createVideoThumbnail(directoryToStore + "/" + SavedVideoName, 3);
File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg"));
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
b.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm trying create a thumbnail from a video, but for some the FileOutputStream returns null.
I have checked the path of File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg")); and it returns the correct path.
The video exists at the location I have given and I have permissions. I can't understand why it is gives me a null pointer?
According to this post, new FileOutputStream() will try to create a new file if it doesn't exist already. From the docs:
If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
When you are debugging (at least in Android Studio), if you add a breakpoint and hover over newFile, it shows the file path. However, it doesn't show any details about the file, because the file doesn't (shouldn't) exist yet. You could try newFile.createNewFile() as suggested in the linked post, to confirm you are able to write the file first.
I am attempting to display PDFs to the user in their browser using a web service. Once they pass in the URL containing the variables needed. My program first downloads the PDF to local storage then proceeds to copy it to the stream and displays it. Once the viewer is able to view the PDF we wish to delete the file locally so that we do not wind up storing every file searched for. I have managed to accomplish most of this task however I am having issues deleting the file once it is displayed to the user.
Even when I attempt to manually delete the file I receive the "Currently in use in the Java SE Binary" message
Code below:
File testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".pdf");
try
{
ServletOutputStream os = res.raw().getOutputStream();
FileInputStream inputStr = new FileInputStream(testFile);
IOUtils.copy(inputStr, os);
os.close();
inputStr.close();
//finished settings
res.status(200);
testFile.delete();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
If you don't write to the file, you'r code should work.
If you call inputStr.close(); the file is no longer used by java and it can be deleted.
Pleace check, if your file is not used by any other programm. It's the best if you reboot your PC.
If it still not works, it would be interessting to know, what res is and if your file get's sendet.
I've read this part of the documentation and i think this should solve your problem.
It reads the file into a String and change the header for png images. As the http Body it uses the String of the file.
Make sure, if you change the response type, you have to change the line res.type("image/png"); to the new one.
Here you find the most common ones
File testFile = null;
try {
testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".png");
FileInputStream fin = new FileInputStream(testFile);
int charAsInt = 0;
String httpBody = "";
while((charAsInt = fin.read()) != -1){
httpBody +=(char)charAsInt;
}
fin.close();
res.body(httpBody);
res.type("image/png");
res.status(200);
testFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drive Quickstart: Run a Drive App in Java example works for uploading files fine. I want to download the files from Gdrive to local system by using java.
For download they are given a method
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
The above method,how can i give inputs? and from where i give the inputs? Can anyone give a complete code for download like Quickstart upload class.
any help will be appreciated.
you can use google drive api and send Http get request, you can see this tutorial
https://developers.google.com/drive/manage-downloads
Thanks Hanan it works fine.By using the retrieveAllFiles() i can list all the documents.And i have stored the retrieved documents in my local by using this below code.Is it a correct way to download.
for(File f:result){
i++;
System.out.println("File Name==>"+f.getTitle());
System.out.println("File Id==>"+f.getId());
System.out.println("File ext==>"+f.getFileExtension());
System.out.println("File size==>"+f.getFileSize());
InputStream in = downloadFile(service,f);
byte b[] = new byte[in.available()];
in.read(b);
java.io.File ff = new java.io.File("/home/test/Desktop/gdocs/"+f.getTitle());
FileOutputStream fout = new FileOutputStream(ff);
fout.write(b);
fout.close();
}
It stores all the documents in local. The text (.txt) files are open properly in my local, but the image files or pdf files are not open properly.It gives some error messages like file corrupted. There is no content in the image or pdf documents how can i get content and store it. Any suggestions
I am trying to write some message to text file. The text file is in the server path. I am able to read content from that file. But i am unable to write content to that file. I am getting FileNotFoundException: \wastServer\apps\LogPath\message.txt (Access Denied).
Note: File has a read and write permissions.
But where i am doing wrong. Please find my code below.
Code:
String FilePath = "\\\\wastServer\\apps\\LogPath\\message.txt";
try {
File fo = new File(FilePath);
FileWriter fw=new FileWriter(fo);
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Hello World");
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this?
Please check whether you can access the apps and LogPath directory.
Type these on Run (Windows Key + R)
\\\\wastServer\\apps\\
\\\\wastServer\\apps\\LogPath\\
And see whether you can access those directories from the machine and user you are executing the above code.
You don't have write access to the share, one of the directories, or the file itself. Possibly the file is already open.
After this line
File fo = new File(FilePath);
try to print the absolute path
System.out.println( fo.getAbsolutePath() );
And then check whether the file exists in that location, instead of directly checking at
\\\\wastServer\\apps\\LogPath\\message.txt
So , you will know, where the compiler is searching for the file.