am create the Excel file to store it in Internal storage,but am not able to do.It Create only inside the app storage directory.Not to visible in public.How to create folder and store the file in that folder?Can anyone one know help me to solve this issue.
File Creation coding
public String generate(String file_name,String path) {
try {
f = new File(activity.getFilesDir(), path);
if (!f.exists()) {
f.mkdirs();
}
file = new File(f.getAbsolutePath(), file_name);
if (file.createNewFile()) {
file.createNewFile();
}
wb_setting = new WorkbookSettings();
wb_setting.setLocale(new Locale("en", "EN"));
workbook = Workbook.createWorkbook(file, wb_setting);
workbook.createSheet("Report", 0);
excelSheet = workbook.getSheet(0);
createLabel(excelSheet);
createContent(excelSheet);
workbook.write();
workbook.close();
file_path_alert_builder = new AlertDialog.Builder(activity);
file_path_alert_builder.setTitle("File path");
file_path_alert_builder.setMessage(""+file).setCancelable(true).setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
file_path_dialog = file_path_alert_builder.create();
file_path_dialog.show();
}catch (JXLException jxl_e) {
jxl_e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
you have to choose the right path where to store the files. There are multiple options
Internal storage
internal to app (not accessible for end users from outside)
cache directory (it can be cleared if system is running out of space)
External Storage (verify if it is available and use it) Although it is public there are 2 types
public
private (technically accessible by the user and other apps because they are on the external storage, they are files that realistically don't provide value to the user outside your app. )
each path location can be accessed with different API provided by android. see http://developer.android.com/training/basics/data-storage/files.html
What you mean by visible to public? Access by other applications? If that is the case, using:
getExternalFilesDir() instead
Related
My app should save files to a place where, when you connect your phone/tablet to a computer, you can see them through the system file explorer.
This is the way I implemented file writing:
protected String mDir = Environment.DIRECTORY_DOCUMENTS;
protected File mPath = Environment.getExternalStoragePublicDirectory(mDir);
protected void writeLogFile(String filename) {
File f = new File(mPath, filename + ".txt");
f.getParentFile().mkdirs();
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f, false))) {
// Details omitted.
} catch (Exception e) {
e.printStackTrace();
return;
}
makeText("Wrote " + f.getAbsolutePath());
}
This is what I see when I connect my Sony Xperia Z4 tablet to Windows (notice missing documents folder):
This is the directory to which the file is written (using above implementation):
What is wrong with my implementation?
What is wrong with my implementation?
MediaStore has not discovered your newly-created files yet. What you see in Windows — and in many on-device "gallery" apps — is based on what MediaStore has indexed.
Use MediaScannerConnection and its scanFile() method to tell MediaStore about your file, once you have written out your data to disk:
public void scanFile(Context ctxt, File f, String mimeType) {
MediaScannerConnection
.scanFile(ctxt, new String[] {f.getAbsolutePath()},
new String[] {mimeType}, null);
}
or, in Kotlin:
fun scanFile(ctxt: Context, f: File, mimeType: String) {
MediaScannerConnection.scanFile(ctxt, arrayOf(f.getAbsolutePath()), arrayOf(mimeType), null)
}
My app should save files to a place where, when you connect your phone/tablet to a computer, you can see them through the system file explorer.
This is the way I implemented file writing:
protected String mDir = Environment.DIRECTORY_DOCUMENTS;
protected File mPath = Environment.getExternalStoragePublicDirectory(mDir);
protected void writeLogFile(String filename) {
File f = new File(mPath, filename + ".txt");
f.getParentFile().mkdirs();
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f, false))) {
// Details omitted.
} catch (Exception e) {
e.printStackTrace();
return;
}
makeText("Wrote " + f.getAbsolutePath());
}
This is what I see when I connect my Sony Xperia Z4 tablet to Windows (notice missing documents folder):
This is the directory to which the file is written (using above implementation):
What is wrong with my implementation?
What is wrong with my implementation?
MediaStore has not discovered your newly-created files yet. What you see in Windows — and in many on-device "gallery" apps — is based on what MediaStore has indexed.
Use MediaScannerConnection and its scanFile() method to tell MediaStore about your file, once you have written out your data to disk:
public void scanFile(Context ctxt, File f, String mimeType) {
MediaScannerConnection
.scanFile(ctxt, new String[] {f.getAbsolutePath()},
new String[] {mimeType}, null);
}
or, in Kotlin:
fun scanFile(ctxt: Context, f: File, mimeType: String) {
MediaScannerConnection.scanFile(ctxt, arrayOf(f.getAbsolutePath()), arrayOf(mimeType), null)
}
m trying to write a file when a button Save_btn is pressed however, when i run the application it runs smoothly with no errors but the file is nowhere to be found.
I am trying to write to the internal storage of the device. the text being written is in a edittext field. i would like this text from the EditText to be written to the file
I have included the code I'm using below;
Save_btn = (Button) findViewById(R.id.g);
Save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View views) {
TextView CodeView = (TextView) findViewById(R.id.Code_Viewer);
CodeView.setText(CodeView.getText());
try {
String etName = CodeView.getText().toString();
if (!etName.trim().equals("")) {
File file = new File("/Documents/test.txt");
//if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(), true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(etName);
bufferWritter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
);
Any advice on how to get the file to write properly would be greatly appreciated.
Thanks in advance.
replace this code with yours :
Save_btn = (Button) findViewById(R.id.g);
Save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View views) {
TextView CodeView = (TextView) findViewById(R.id.Code_Viewer);
CodeView.setText(CodeView.getText());
String etName = CodeView.getText().toString();
File dir = new File(getFilesDir(), "yourfolder");
if(!dir.exists())
{
dir.mkdirs();
}
String textFileName="textFile.txt";
File file = new File(dir.getPath(), textFileName );
if(file.exists())
{
file.delete();
}
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(etName);
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
);
you should note these points :
this code will create file on /data/data/[your app package name]/files/[your folder]/[your textFileName]
it always remove your file if the file name was the same , so you should get unique name for each one.(you can include date and time in file name)
I'm not sure this can work because the file path you're specifying is a) absolute and b) pointing to a directory you probably have no write permission for.
File file = new File("/Documents/test.txt");
This references the Documents folder in the file systems root directory instead of your apps files.
If you want to save it locally for use in your own application, you can try Context#getFilesDir, e.g.
File file = new File(context.getFilesDirectory(), "yourfile.txt");
In case you want to save it somewhere other applications can use it you might need a more sophisticated approach, e.g. a FileProvider.
You should use
File file = new File(context.getFilesDir(), "test.txt");
instead of
File file = new File("/Documents/test.txt");
to save to your internal storage. The rest of your code can stay the same.
I am working on an android game. I want to copy a text file to external SD card when the user installs the game for the first time. The text file is important for properly running the game.
How can I do that? Where should i place the text file in eclipse source project so that when i build the apk file, my text file also gets bundled in it and when a use installs application from that apk file the text file gets copied to "SDcard\data" folder.?
What code should i write and where, so that it gets executed only once at installation time.
Thanks in advance
This is the methods I use to copy a file to the sd card when the app is first installed:
public class StartUp extends Activity {
/**
* -- Called when the activity is first created.
* ==============================================================
**/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirstRun();
}
private void FirstRun() {
SharedPreferences settings = this.getSharedPreferences("YourAppName", 0);
boolean firstrun = settings.getBoolean("firstrun", true);
if (firstrun) { // Checks to see if we've ran the application b4
SharedPreferences.Editor e = settings.edit();
e.putBoolean("firstrun", false);
e.commit();
// If not, run these methods:
SetDirectory();
Intent home = new Intent(StartUp.this, MainActivity.class);
startActivity(home);
} else { // Otherwise start the application here:
Intent home = new Intent(StartUp.this, MainActivity.class);
startActivity(home);
}
}
/**
* -- Check to see if the sdCard is mounted and create a directory w/in it
* ========================================================================
**/
private void SetDirectory() {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File txtDirectory = new File(extStorageDirectory + "/yourAppName/txt/");
// Create
// a
// File
// object
// for
// the
// parent
// directory
txtDirectory.mkdirs();// Have the object build the directory
// structure, if needed.
CopyAssets(); // Then run the method to copy the file.
} else if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED_READ_ONLY)) {
AlertsAndDialogs.sdCardMissing(this);//Or use your own method ie: Toast
}
}
/**
* -- Copy the file from the assets folder to the sdCard
* ===========================================================
**/
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for (int i = 0; i < files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(files[i]);
out = new FileOutputStream(extStorageDirectory + "/yourAppName/txt/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
For this target the best way is make SharedPreferences or your file must be added in "assets" directory in android project.
as per link
There is the ACTION_PACKAGE_ADDED Broadcast Intent, but the application being installed doesn't receive this.
So it looks using SharedPreferences is the easiest way...
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
boolean firstRun = p.getBoolean(PREFERENCE_FIRST_RUN, true);
p.edit().putBoolean(PREFERENCE_FIRST_RUN, false).commit();
Put the file in the assets folder. Then, using whatever logic you come up with, when your app launches determine if it is the first run of the app.
If it is you can use getAssets() from an Activity to access the asset file and just copy it to wherever necessary.
Since the file on the sdcard is something that could be accidentally deleted by the user, you should probably check directly for its presence (and possibly verify contents) rather than trying to use something independent such as a shared preference to tell if this is the first run of the activity.
For purposes of potential app upgrades, you should probably put a version number in the file, and check that.
If the file is something you want to let power users manually edit (to change expert options) then you may have a little bit of a challenging situation to handle on upgrade.
i have a problem with my code that is supposed to write some data string to my sdcard. i use a class to do this:
public class CVS {
private String path;
private String filename;
private File dir;
private File file;
private FileWriter fw;
public CVS() {
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/traffic/";
filename = "data.cvs";
file = new File(path, filename);
createDir();
}
private void createDir() {
dir = new File(path);
if(!dir.exists()) {
if(file.mkdirs() == false) {
Log.d(Config.LOGTAG, "UHOH!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
else Log.d(Config.LOGTAG, "dir exists");
}
public void writeToFile(String data) {
try {
fw = new FileWriter(file);
fw.append(data); Log.d(Config.LOGTAG, "data saved to file...");
}
catch(Exception e) {
Log.d(Config.LOGTAG, "file: " + e.getMessage());
}
}
}
this results ALWAYS in an exeption being caught in writeToFile(), saying "permission denied". actually, i set permissions to WRITE_EXTERNAL_STORAGE in the manifest. so - what am i doing wrong!?
additional info: real device with sd card mounted. no emulator. android 2.2. if i create the dir myself, the problem wont go away :(
Either:
Your manifest is wrong, or
Your external storage is mounted on your development machine, or
Your manual concatenation of your directory is wrong
Your code is ok but still you can add a check for whether sdcard is inserted or not, if you run this code and sdcard is not inserted then it will throw an exception, good practice is that you should always catch the exeptions.
you can check sdcard by following code...
if (android.os.Environment.getExternalStorageState().equals
(android.os.Environment.MEDIA_MOUNTED))
{
//code or logic if sd card is inserted....
}
else
{
Log.e("Exception","SD Card not found!");
}
All of the answers are needed, but if it's a Samsung device, then you need to append "/external_sd/" to the path - because they decided they needed to dork with our minds and break the API:
"http://developer.samsung.com/forum/board/thread/view.do?boardName=GeneralB&messageId=162934&messageNumber=1381&startId=zzzzz~&searchType=TITLE&searchText=sdcard