writing and saving a file in android application - android

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.

Related

Why is the filelist array null in Java with Android Studio?

I am using Android Studio with Java.
I have written a method (namely deleteWithExtension) to delete files from device internal memory. This method is adding some test files and tries to get the listof these files.
But the problem is that, the code never goes in the for-loop because of the array theFiles[] returns null. As you can see that, the code begins with sample files adding process so it should not be empty. I can also see those sample files in the Device File Explorer of Android Studio.
public static void CreateFile(Context mContext, String fileName, String textToBeWritten) {
try {
File dosya = new File(mContext.getFilesDir() + fileName);
dosya.createNewFile();
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write(textToBeWritten);
yazici.flush();
yazici.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void deleteWithExtension(Context mContext, String extension) {
//First let's add a few sample files with same extension.
CreateFile(mContext,"SampleFile1.smp","anything1");
CreateFile(mContext,"SampleFile2.smp","anything2");
CreateFile(mContext,"SampleFile3.smp","anything3");
CreateFile(mContext,"SampleFile4.smp","anything4");
CreateFile(mContext,"SampleFile5.smp","anything5");
//Now, 5 sample files have been added. Let get them and put in an array.
File dir = mContext.getFilesDir();
final String[] theFiles = dir.list();
for (final String file : theFiles) {
//do something here....
int aa=9;
//The code never goes into here, because array theFiles is always null but 5 sample files was added at first.
}
}
replace the CreateFile() method as follows. I hope I can help you.
public static void CreateFile(Context mContext, String fileName, String textToBeWritten) {
try {
File dosya = new File(mContext.getFilesDir() + File.separator + fileName);
dosya.createNewFile();
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write(textToBeWritten);
yazici.flush();
yazici.close();
} catch (Exception e) {
e.printStackTrace();
}
}

How should I save a json into my external storage?

I implemented a share button in my app. When I want to share, I can select a saved json data from the device and select via which way I want to share it (mail etc.). The problem is, that the data is NOT in the attachements. The problem is likely because I use the internal app storage. Therefore I want to save tje json data into the external storage, what would be better in my case anyway. But I am not really sure how to do that. I am not sure if I should use the Media type of content of the Documents and other files type of content which is provided by android. There is also the Appspecific files type but this looks like it is not applicaple for me, because I need to share the json data wit ha share functin. At the moment my code looks like this:
Save Function, which get's a file name I can choose myself
private void saveState(String name) {
File file = new File(getFilesDir(), name + ".json");
try{
OutputStream out = new FileOutputStream(file);
MyJsonWriter writer = new MyJsonWriter();
writer.writeJsonStream(out, ... //data structure);
out.close();
}catch (Exception e){
Log.e("saveState ERROR", "----------------------------------------------------");
}
}
LoadButtonClick Functin which shows me all files
public void loadStateClick(View view) {
final LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
String[] files = MainActivity.this.fileList();
... //more code which is not important here
Load Function
private void loadState(String name) {
File file = new File(getFilesDir(), name);
InputStream in = null;
... //setting my data structure, not important here
try{
in = new FileInputStream(file);
MyJsonReader reader = new MyJsonReader(MainActivity.this);
SaveData savedData = reader.readJsonStream(in);
... // handling data structure, not important here
in.close();
}catch (Exception e){
Log.e("LOAD ERROR", e.toString());
}
}

Android app - how to write to Android device's Documents folder?

I want to create a XML file inside my Android app.
This file I want to write into the documents folder of my Android device.
Later I want to connect my Android device to my PC using USB and read that XML file out of the documents folder.
My Device is an Android Galaxy Tab Pro 10.1, Android 4.4.2.
I tried already:
String fileName = "example.xml";
String myDirectory = "myDirectory";
String externalStorage = Environment.getExternalStorageDirectory().getAbsolutePath();
File outputFile = new File(externalStorage + File.separator + myDirectory + File.separator + fileName);
But no file is created. I also want later to read that file out of the documents folder into may app again.
Any help is appreciated, thanks!
I know this is late, but you can get the documents directory like this:
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File file = new File(dir, "example.txt");
//Write to file
try (FileWriter fileWriter = new FileWriter(file)) {
fileWriter.append("Writing to file!");
} catch (IOException e) {
//Handle exception
}
Set permission in Android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use this code to write to external directory
String fileName = "example.xml";
String dirName = "MyDirectory";
String contentToWrite = "Your Content Goes Here";
File myDir = new File("sdcard", dirName);
/*if directory doesn't exist, create it*/
if(!myDir.exists())
myDir.mkdirs();
File myFile = new File(myDir, fileName);
/*Write to file*/
try {
FileWriter fileWriter = new FileWriter(myFile);
fileWriter.append(contentToWrite);
fileWriter.flush();
fileWriter.close();
}
catch(IOException e){
e.printStackTrace();
}
Before creating file you have to create directory in which you are saving the file.
Try like this one:-
String fileName = "example.xml";
String myDirectory = "myDirectory";
String externalStorage = Environment.getExternalStorageDirectory().getAbsolutePath();
File outputDirectory = new File(externalStorage + File.separator + myDirectory );
if(!outputDirectory.exist()){
outputDirectory.mkDir();
}
File outputFile = new File(externalStorage + File.separator + myDirectory + File.separator + fileName);
outputFile.createFile();
Try restarting you device and then check if the file exists. If so, you are creating it (which it looks like you should be based on your code) but it is not showing up until the media is scanned on your device. Try implementing MediaScannerConnectionClient so it will show become visible after creation.
public class MainActivity extends Activity implements MediaScannerConnectionClient {
private MediaScannerConnection msConn;
private File example;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
msConn = new MediaScannerConnection(this.getApplicationContext(), this);
String dir = Environment.getExternalStorageDirectory() + "/Documents/";
example = new File(dir, "example.xml");
msConn.connect();
}
#Override
public void onMediaScannerConnected() {
msConn.scanFile(example.getAbsolutePath(), null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
}
From Android 10 onwards, Android started using Scoped Storage model to protect user privacy.
If you want to share this file with the User, then you should write this file in Shared Storage. To write a file in Shared Storage, this has to be done in 3 steps:-
Step 1: Launch System Picker to choose the destination by the user. This will return Uri of the destination directory.
private ActivityResultLauncher<Intent> launcher; // Initialise this object in Activity.onCreate()
private Uri baseDocumentTreeUri;
public void launchBaseDirectoryPicker() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
launcher.launch(intent);
}
Step 2: Launch System Picker to choose the destination by the user. This will return the Uri of the destination directory. Also, you can optionally persist the permissions and Uri for future use.
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
baseDocumentTreeUri = Objects.requireNonNull(result.getData()).getData();
final int takeFlags = (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// take persistable Uri Permission for future use
context.getContentResolver().takePersistableUriPermission(result.getData().getData(), takeFlags);
SharedPreferences preferences = context.getSharedPreferences("com.example.fileutility", Context.MODE_PRIVATE);
preferences.edit().putString("filestorageuri", result.getData().getData().toString()).apply();
} else {
Log.e("FileUtility", "Some Error Occurred : " + result);
}
}
Step 3: Write CSV content into a file.
public void writeFile(String fileName, String content) {
try {
DocumentFile directory = DocumentFile.fromTreeUri(context, baseDocumentTreeUri);
DocumentFile file = directory.createFile("text/*", fileName);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(file.getUri(), "w");
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
}
}
For more explanation, you can read "How to Save a file in Shared Storage in Android 10 or Higher" or Android official documentation.

Adding folder in Internal Storage in public?

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

Where does Robolectic on Android, save files created during test runs?

I want to ensure a byte array is being converted to a jpg correctly.
I've simplified the problem as follows:
public String saveToFile(String filename, String contents) {
String storageState = Environment.getExternalStorageState();
if(!storageState.equals(Environment.MEDIA_MOUNTED)) {
throw new IllegalStateException("Media must be mounted");
}
File directory = Environment.getExternalStorageDirectory();
File file = new File(directory, filename);
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file, false);
fileWriter.write(contents);
fileWriter.close();
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Test
public void testDummyTest() throws Exception{
String out = saveToFile("preview-test.jpg", "preview-test.jpg");
}
This test passes and the path is something like file:///var/folders/z_/_syx1dpx7v9_pmktgdbx7f_m0000gn/T/android-external-cache8656399524188278404robolectric/ddf1c2ec-c0a8-44ce-90e4-7de2a384c57f/preview-test.jpg
However, I can't find this file my machine (yes, I've searched for it). I suspect this is a temp cache and its being cleared/deleted before I can view it.
Please can you tell me how to locate the "preview-test.jpg" file so I may open it in an image viewer, thus proving the image looks like it should. Thanks.
Note: the problem is not the jpg encoding, its simply getting direct access to the file.
I found a partial solution.
Rather than using the shadow environment to provide a path, I can instead use an absolute path for the machine. Eg root "/" would work.
So the code would look something like...
public String saveToFile(String filename, String contents) throws IOException {
File file = new File("/", filename);
FileWriter fileWriter;
fileWriter = new FileWriter(file, false);
fileWriter.write(contents);
fileWriter.close();
return file.getAbsolutePath();
}
#Test
public void testDummyTest() throws Exception {
String out = saveToFile("preview-test.jpg", "preview-test.jpg");
}
This then leaves a file on the root directory of the machine. :) Hope this helps somebody else out there.

Categories

Resources