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

Apps Reading/Writing Text File

crazyfool_1

Newbie
Jan 25, 2011
12
0
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.
 
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();
	}
}
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones