Error when call write() - android

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);

Related

Unable to create file in Android app

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");

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.

Folder on phone not showing in Windows PC

I am writing an app to create a folder on my Nexus 5 and then write a text file inside the folder.
The above part is working just fine. I am writting using the following code:
Creating the folder:
File sdCard1 = Environment.getExternalStorageDirectory();
File dir = new File(sdCard1.getAbsolutePath() + "/SmsApp");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
File sdCard = Environment.getExternalStorageDirectory();
directory = new File (sdCard.getAbsolutePath() + "/SmsApp");
directory.mkdirs();
And writing the string to text file.
public void writeToText(String texttosave)
{
File sdCard = Environment.getExternalStorageDirectory();
File logFile = new File(sdCard.getAbsolutePath() + "/SmsApp" + "/smsrawdata.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(texttosave);
buf.newLine();
buf.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Text file is showing up properly on my phone but when I am trying to access the same folder on phone I can't see the folder at all.
I thought it would be the same for other app on play store that creates a folder but then everything gets created and then I can see them on Windows Explorer.
Am I doing something wrong in the code part for it not to show on my Computer but show only on my phone. I am using ES File Explorer to see files on my phone.
Please let me know if someone else is having the same problem.
Thanks!
Your pc will communicate with the media store about files. Not directly with the sdcard or external memory. If the media store does not know about your file your pc can not see it. You forgot to tell the store that you created a file. For every new file you should invoke the media scanner for that file. You are not the first one who happens this so the problem has been reported many times. You only need to add a few lines of code which you will find easily searching this site for invoking media scanner on new file. If you switch off/on your device the file will be known soon too.

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.

Check if file exists on SD card on Android

I want to check if a text file exists on the SD card. The file name is mytextfile.txt. Below is the code:
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
How can I check whether this file exists?
This should do the trick, I've replaced the hard coded SDcard reference to the recommended API call getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}
See this file System in android : Working with SDCard’s filesystem in Android
you just check
if(file.exists()){
//
}
*Using this you can check the file is present or not in sdcard *
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
You have to create a file, and set it to be the required file, and check if it exists.
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
Have Fun!
The FileOutputStream constructor will throw a FileNotFound exception if the specified file doesn't exist. See the Oracle documentation for more information.
Also, make sure you have permission to access the SD card.
check IF condition with Boolean type like
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}

Categories

Resources