I want to write something to a file. I found this code:
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new Ou
Write one text file simplified:
private void writeToFile(String content) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.flush();
writer.close();
} catch (IOException e) {
}
}
You can write complete data in logData in File
The File will be create in Downlaods Directory
This is only for Api 28 and lower .
This will not work on Api 29 and higer
@TargetApi(Build.VERSION_CODES.P)
public static File createPrivateFile(String logData) {
String fileName = "/Abc.txt";
File directory = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/");
directory.mkdir();
File file = new File(directory + fileName);
FileOutputStream fos = null;
try {
if (file.exists()) {
file.delete();
}
file = new File(getAppDir() + fileName);
file.createNewFile();
fos = new FileOutputStream(file);
fos.write(logData.getBytes());
fos.flush();
fos.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/
).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
You might want to dig into the subject, by reading the official docs
In synthesis:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It includes the READ permission, so no need to specify it too.
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
Environment.DIRECTORY_DCIM + "/YourFolder/"
);
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
[EDIT] OK Try like this (different path - a folder on the external storage):
String path =
Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
// Create the folder.
File folder = new File(path);
folder.mkdirs();
// Create the file.
File file = new File(folder, "config.txt");
This Method takes File name & data String as Input and dumps them in a folder on SD card. You can change Name of the folder if you want.
The return type is Boolean depending upon Success or failure of the FileOperation.
Important Note: Try to do it in Async Task as FIle IO make cause ANR on Main Thread.
public boolean writeToFile(String dataToWrite, String fileName) {
String directoryPath =
Environment.getExternalStorageDirectory()
+ File.separator
+ "LOGS"
+ File.separator;
Log.d(TAG, "Dumping " + fileName +" At : "+directoryPath);
// Create the fileDirectory.
File fileDirectory = new File(directoryPath);
// Make sure the directoryPath directory exists.
if (!fileDirectory.exists()) {
// Make it, if it doesn't exist
if (fileDirectory.mkdirs()) {
// Created DIR
Log.i(TAG, "Log Directory Created Trying to Dump Logs");
} else {
// FAILED
Log.e(TAG, "Error: Failed to Create Log Directory");
return false;
}
} else {
Log.i(TAG, "Log Directory Exist Trying to Dump Logs");
}
try {
// Create FIle Objec which I need to write
File fileToWrite = new File(directoryPath, fileName + ".txt");
// ry to create FIle on card
if (fileToWrite.createNewFile()) {
//Create a stream to file path
FileOutputStream outPutStream = new FileOutputStream(fileToWrite);
//Create Writer to write STream to file Path
OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(outPutStream);
// Stream Byte Data to the file
outPutStreamWriter.append(dataToWrite);
//Close Writer
outPutStreamWriter.close();
//Clear Stream
outPutStream.flush();
//Terminate STream
outPutStream.close();
return true;
} else {
Log.e(TAG, "Error: Failed to Create Log File");
return false;
}
} catch (IOException e) {
Log.e("Exception", "Error: File write failed: " + e.toString());
e.fillInStackTrace();
return false;
}
}