How to Create Text File and Insert Data to That File on Android

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



Leave a reply



Submit