• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Reading/Writing Text File

hey guys, My app is coming along really nicely but atm i'm stuck on this. I cannot work out how to read and write to a text file. Everything I have tried force closes so obviously something isn't write. If anyone could show me or point me in the right direction (not the android documentation though as I find it to be very lacking in explanation) it would be appreciated.
 
First things first, did you add the permission to write to files in the manifest?

You need to add this line to the manifest's root to be able to write to files on the SD Card:

Code:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 
All the code I had I deleted because it was force closing and I'm pretty certain it wasn't at all correct. I basically just need a basic example of reading and writing to a file and I can do the rest from there.
 
Well, ok... Here is some code you can look at. I made it for at project at the university. Don't mind all the things regarding the PPLogger class (which basically just returns Strings or arrays of Strings). But anyways, this saves whatever String added to outer.Write("String") to a .txt located on the SDCard in the path named "path":

Code:
private void saveToFile(PPLogger log, String filename){
	String exStorageState = Environment.getExternalStorageState();
	if (Environment.MEDIA_MOUNTED.equals(exStorageState)){
		try {
			File root = Environment.getExternalStorageDirectory();
				
			// Test if the path exists
			String path = root+"/PerversePositions/log/";
			boolean exists = (new File(path).exists());
			// If not, create dirs
			if (!exists) {new File(path).mkdirs();}
			// Open the file and a writer
			Date time = new Date();
				
			File logFile = new File(path+filename+"-"+time.getHours()+"-"+time.getMinutes()+"-"+time.getSeconds()+".txt");
			logFile.createNewFile();
			FileWriter logWriter = new FileWriter(logFile);
			BufferedWriter outer = new BufferedWriter(logWriter);
			// Write log entries to file
			ArrayList<PPLogEntry> entries = log.getLog();
			outer.write("Number of GPS fixes: " + log.getFixes());
			outer.write("\r\n");
			outer.write("Number of log entries: " + entries.size());
			outer.write("\r\n");
			for (PPLogEntry entry : entries) {
				outer.write(entry.toString());
				outer.write("\r\n");
			}
			outer.close();
			System.out.println("PP SERVICE --- Log saved");
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(this, "Couldn't save", Toast.LENGTH_SHORT);
		}
	}
	else{
		//FAIL
		System.out.println("File not accessible");
		Toast.makeText(this, R.string.pp_omni_file_not_accessible, Toast.LENGTH_SHORT).show();
	}
}
 
Back
Top Bottom