How to create text file and insert data to that file on Android
Using this code you can write to a text file in the SDCard.
Along with it, you need to set a permission in the Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is the code :
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.
Environment.getExternalStorageState()
Creating a Text File in Android results in FileNotFoundException
Have you tried adding:
android:requestLegacyExternalStorage="true"
to your manifest in <application>
tag?
Also, don't forget that from Android 6.0 you need to request permissions even if you write them in your Manifest.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] permissions = new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE};
for (int i = 0; i < permissions.length; i++) {
if (checkSelfPermission(permissions[i]) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions,
REQUEST_PERMISSIONS);
return;
}
}
}
How to add data to an existing .txt file in android
Try this code. Set second argument of FileWriter to true. Thus you can append your existing file
File file = new File("Hello.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file,true);
writer.write("Writes the content to the file");
writer.flush();
writer.close();
Read/Write String from/to a File in Android
Hope this might be useful to you.
Write File:
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Read File:
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
How to create files to a specific folder in android application?
use getCacheDir(). It returns the absolute path to the application-specific cache directory on the filesystem. Then you can create your directory
File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();
Please try this maybe helps you.
Ok, If you want to create the TextFile in Specific Folder then You can try to below code.
try {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MyFolder/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
File f = new File(rootPath + "mttext.txt");
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Write text file in the device's storage
You have to write the file in public directory like Document
, Download
or others.
String fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = "kontaktebi123.vcf";
File file = new File(fileDir + "/" + fileName);
Now write in the file and it will be visible to other apps.
Related Topics
React-Native: Command Not Found
How to Take a Screenshot of a Current Activity and Then Share It
How to Create Edittext with Rounded Corners
How to Prevent a Service from Being Killed by Os
Didn't Find Class "Com.Google.Firebase.Provider.Firebaseinitprovider"
How to Get the List of Running Applications
How to Set Entire Application in Portrait Mode Only
Webview Shouldinterceptrequest Example
No Internet on Android Emulator - Why and How to Fix
Adb Not Responding - Wait More or Kill Adb or Restart (Ubuntu 13) 64-Bit
Install Shows Error in Console: Install Failed Conflicting Provider
Android Get Image from Gallery into Imageview
How to Handle Handler Messages When Activity/Fragment Is Paused
Android: Binding Data from a Database to a Checkbox in a Listview
Android Studio Says "Cannot Resolve Symbol" But Project Compiles
Android 2.2 Mediaplayer Is Working Fine with One Shoutcast Url But Not with the Other One
How to Change Color of Textinputlayout's Label and Edittext Underline Android