Unable to create file in Android app - android

I am making a android app in which i am going to use File handling but to do that first i need to create it but by using following code:
File logf = new File("log1.txt");
Boolean bb = logf.exists();
if(!bb)
try {
bb = logf.createNewFile();
} catch (IOException e) {
msg.setText("not able to create file.");
}
'msg' is the TextView object which i am using to display error, and when i run this app.. it goes into IOException e catch.. Please tell me if i am doing something wrong or what?.. besides i am using Android 2.2 for my app.

In app storage, please try this:
File file = new File(getFilesDir(), "file.txt");
Or if you want to append file name, try this:
File file = new File(getFilesDir() + File.separator + "file.txt");

you need to provide absolute path of file like below.
File file = new File(/data/packagename/files/ + "log1.txt");

Related

Android: Create and Download PDF files to Downloads directory

In my Android App, in one of the activity, there is a "PDF Download" button. When this button is clicked, I create a PDF and then download it to the "Downloads" directory. Following is my code which runs on the click event of the button:
public void createAndDownloadPDF()
{
try
{
PdfDocument document = new PdfDocument();
View content = this.findViewById(android.R.id.content);
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(content.getWidth(),
content.getHeight() - 20, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
content.draw(page.getCanvas());
document.finishPage(page);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdfdemo"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), pdfName);
try
{
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
document.writeTo(out);
document.close();
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Please note that I added the required WRITE permission to the MANIFEST file and also asking for the permission at runtime. So, there is no issue of permissions.
When I debug the code, I notice that "outputFile" variable holds this path:
/storage/emulated/o/Download/pdfdemo07052017121233.pdf
My users will never find above path in their mobile. So, they will have no clue where their PDF got saved. I want that when users click on "Downloads" icon on their mobile, they should see the PDF file they downloaded from the app.
So, I think if I can sort out the following line:
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), pdfName);
my work will be done. What should be the path I use so that my PDF files get saved / downloaded in the "Downloads" directory? I researched over the internet, but did not find any concrete solution.
Try this:
File outDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
If this doesn't work, evaluate the chance of having your PDF file previously generated and saved into a folder inside your Assets folder. If this can be the case, after the above line you insert this:
copyAssets("XXX",outDir.toString());
Where "XXX" is the name of the folder inside your Assets folder which will contain the PDF file. This will copy the contents of XXX to DOWNLOADS/XXX on your device.

Creating a file unsing openFileOutput() which is visible to other applications

I'm using the openFileOutput() to create a new txt file. I need the file to be visible from other applications (as well as from a PC when the Android device is connected via USB. Ive tried using .setReadable(true); but this does not seem valid. Please advise how I should declare the file is visible / public.
try {
textIncoming.append("saving");
final String STORETEXT = "test.txt";
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.setReadable(true);
out.write("testing");
out.close();
}
catch (Throwable t) {
textIncoming.append("not saving");
}
Ive changed my program to use getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), but for some reason it returns a path /storage/emulated/0/Documents, and I cant even find this folder on the device. Ive looked at the files on the android device using ES file explorer but cant find the folder or file I'm trying to create (Plus I want these in an documents folder on the SD card, so it seems that its not giving me a pointer to the SD card at all, and not creating the folder, and not creating the file. Following is my updated code, please advise
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File myDir = new File(root + "/Saved_Receipts");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "DRcpt-" + n + ".xml";
textIncoming.append(root);
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
Save it to sdcard if you want anyone to be able to read it.
This android documentation should tell you what you need to do.
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
openFileOutput() documentation says:
Open a private file
So the file that it creates won't be visible to other apps, unless you copy it to another directory that is visible. In that case, you have to save your data in what's called "external storage" which is shared with other apps. Use the code at this link.

unable to open a word file using android app

I have saved a file with .docx extension in my app.the file is saved in the sdcard. The file appears as a word file in my sdcard but I am unable to open it (using polaris or any other default software) and message"unsupported file" appears.
When I save the file with .txt extension, I can open it.
public void Savedoc(View v)
{
String filename = "file" + sn + ".docx";
String filepath = "MyFileStorage";
myExternalFile = new File(getExternalFilesDir(filepath), filename);
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(ly.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
thank you alexandru ...but now i get an error message on running the app stating "The Javadoc for this element could neither be found in the attached source nor the attached Javadoc".pls help...
You'll need to use Apache POI in order to correctly create a .docx file.
I've found this answer with a code snippet:
XWPFDocument document = new XWPFDocument();
XWPFParagraph tmpParagraph = document.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();
tmpRun.setText("LALALALAALALAAAA");
tmpRun.setFontSize(18);
document.write(new FileOutputStream(new File("yourpathhere")));
You may find more information about how to use XWPF here.

Get object File from a file in raw folder

What i want to do is very simple :
String dataDir = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).applicationInfo.dataDir;
Log.e(TAG , "dataDir = " + dataDir);
File tmpFile = new File(dataDir + "/raw/ocr.jpg");
But i got a file not found exception
i NEED an object file as after i do
photoUriString = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), tmpFile.getAbsolutePath(), null, null);
(because i want to share the picture on google+, see How to share image in google Plus through an android app?)
So please don't tell me about a reader, a bufferedReader, etc ...
Thanks
InputStream is = getResources().openRawResource(R.raw.ocr.jpg));
you have to get the InputStream through openRawResource, then you can manage it as you need

Error when call write()

I have error in line:
workbook.write();
When I try debug, i see massage: "Source not found."
How it fix?
private void exportExcel() throws IOException, WriteException{
File file = new File(Environment.getExternalStorageDirectory() + "/backup.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
}
Thanks in advance
WTF my code above begin to work!!!
When I started, I using default jexcelapi. Afterwards I begin using alternative jexcelapi, but it also not work.
When I try your code with little changes - it work! Your code:
private void exportExcel() throws WriteException, IOException{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard + "/myFolder");
//make them in case they're not there
dir.mkdirs();
//create a standard java.io.File object for the Workbook to use
File wbfile = new File(dir, "backup.xls");
WritableWorkbook workbook = null;
try{
workbook = Workbook.createWorkbook(wbfile);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
} catch (IOException ex) {
Log.e("Workbook Test", "Could not create " + wbfile.getPath(), ex);
}
}
But when I try my code above, it also work.
Maybe Eclipse not instantly update using library?
Thank you very much!
P.S. Excuse me for my bad english.
Your code does not check that the external storage directory is actually available. You need to call getExternalStorageState and check the return value against the various MEDIA_* values defined in Environment. If the directory is not available, that may cause the problem.
The problem also may be that you are trying to write to the root of the external storage directory. From the docs:
Applications should not directly use this top-level directory, in order to avoid polluting the user's root namespace. Any files that are private to the application should be placed in a directory returned by Context.getExternalFilesDir, which the system will take care of deleting if the application is uninstalled.
EDIT
Try this code:
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard + "/myFolder");
//make them in case they're not there
dir.mkdirs();
//create a standard java.io.File object for the Workbook to use
File wbfile = new File(dir, "backup.xls");
try{
WritableWorkbook workbook = Workbook.createWorkbook(wbfile);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
} catch (IOException ex) {
Log.e("Workbook Test", "Could not create " + wbfile.getPath(), ex);
}
return wb;
That should tell you more about what's going on.
EDIT 2
After a little more research, I found another possible issue: JExcelApi uses a lot of resources when it is creating a file. One solution is to use a temp file. Add the following code:
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setUseTemporaryFileDuringWrite(true);
and inside the try block, change the line that creates the workbook:
WritableWorkbook workbook = Workbook.createWorkbook(wbfile, wbSettings);

Categories

Resources