Saving a bunch of integers to file android - android

So I have a bunch of EditText fields that I need the user to enter in. After this is done I want to save all the input-values to a file and make them loadable by clicking on them in another tab.
I'm kinda lost though.
I have about 5 EditText fields that I convert to ints (they are inputting ints) and then calculating different values from them. I want to save these values in int form. How do I achieve this easiest way? I'm only finding how to save strings.
If I want to save every click on the "calculate" button to a different file (if the user changes a input value and clicks calculate again I want a second file to be made with those values). How do I achieve creating a lot of files that are different (or the same if the button gets spammed).
Thirdly, how can I show what files there are to be loaded from the directory?

To write the text of all the edittext you have to use following code:
// write text to file
public void WriteBtn(String finalString) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(finalString.toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
To read the text from file following code can be usefull:
// Read text from file
public String ReadBtn() {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[100];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
return s;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}

Related

Android Studio read/write from .txt file, save path?

so im trying to write data that I recieve from a socket into text file and then read those data.
I have these 2 methods in my MainActivity (just tests to see how read and write from/into a file works) :
public void WriteBtn() {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("Test");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ReadBtn() {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[256];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
I call them with buttons but I was wondering, where does it save my "mytextfile.txt" ???
Take a look at Context.getExternalFilesDir() and pass it Environment.DIRECTORY_DOCUMENTS. That should give you the default output path for text files.
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
EDIT
I just tested this. It looks like Context.openFileOutput() dumps everything, regardless of file type, to Conext.getFilesDir()
https://developer.android.com/reference/android/content/Context.html#getFilesDir()

read file from the assets folder

I have a large text file that is in the assets folder, and I have a button that reads the file's next line successfully. However, I want to read the previous line in case the user clicks another button.
Reading the whole file to memory is not an option. The file lines are not numbered.
InputStream is = getResources().getAssets().open("abc.txt");
String result= convertStreamToString(is);
public static String convertStreamToString(InputStream is)
throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[2048];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String text = writer.toString();
return text;
}
If you only need to keep track of one previous line, you can do something like the following, keeping track of the previous line through each iteration (I assumed you were using a reader; for this example, BufferedReader):
String previous = null, line; // null means no previous line
while (line = yourReader.readLine()) {
// Do whatever with line
// If you need the previous line, use:
if (yourCondition) {
if (previous != null) {
// Do whatever with previous
} else {
// No previous line
}
}
previous = line;
}
If you need to keep track of more than one previous line, you may have to expand that into an array, but you will be keeping a huge amount in memory if your file is large--as much as if you'd read the entire file, once you get to the last line.
There is no simple way in Java or Android to read the previous line, only the next (as it is easier in file I/O to more forward than backward).
One alternative I can think of is to keep a line marker (starting at 0), and as you advance through the lines, increase it. Then, to go backwards, you have to read the file line by line again, until you get to that line minus one. If you need to go backwards, go to that new line minus one, and so on. It would be a heavy operation, most likely, but would suit your needs.
Edit: If nothing above will work, there is also a method to read in a file backwards, in which you may be able to use to find the previous line by iterating forward. Just an alternative idea, but definitely not an easy one to implement.
public class LoadFromAltLoc extends Activity {
//a handle to the application's resources
private Resources resources;
//a string to output the contents of the files to LogCat
private String output;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get the application's resources
resources = getResources();
try
{
//Load the file from the raw folder - don't forget to OMIT the extension
output = LoadFile("from_raw_folder", true);
//output to LogCat
Log.i("test", output);
}
catch (IOException e)
{
//display an error toast message
Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG);
toast.show();
}
try
{
//Load the file from assets folder - don't forget to INCLUDE the extension
output = LoadFile("from_assets_folder.pdf", false);
//output to LogCat
Log.i("test", output);
}
catch (IOException e)
{
//display an error toast message
Toast toast = Toast.makeText(this, "File: not found!", Toast.LENGTH_LONG);
toast.show();
}
}
//load file from apps res/raw folder or Assets folder
public String LoadFile(String fileName, boolean loadFromRawFolder) throws IOException
{
//Create a InputStream to read the file into
InputStream iS;
if (loadFromRawFolder)
{
//get the resource id from the file name
int rID = resources.getIdentifier("fortyonepost.com.lfas:raw/"+fileName, null, null);
//get the file as a stream
iS = resources.openRawResource(rID);
}
else
{
//get the file as a stream
iS = resources.getAssets().open(fileName);
}
//create a buffer that has the same size as the InputStream
byte[] buffer = new byte[iS.available()];
//read the text file as a stream, into the buffer
iS.read(buffer);
//create a output stream to write the buffer into
ByteArrayOutputStream oS = new ByteArrayOutputStream();
//write this buffer to the output stream
oS.write(buffer);
//Close the Input and Output streams
oS.close();
iS.close();
//return the output stream as a String
return oS.toString();
}
}

Managing text files Android

I've got a little problem while managing .txt files on Android. I've found this link (it's in Spanish) that explains how to use text files on my Android device.
What I want to do, is create a text file using the intern memory of the device, as I don't want the user depend on a SD card, and a raw text file won't allow me to write on in, only read. So I want a text file that can append some information and, in a particular case, delete all the content in the text file and reset it.
I've written this code for the writing side:
OutputStreamWriter fout = null;
try
{
fout = new OutputStreamWriter(openFileOutput("measures.txt", Context.MODE_APPEND));
fout.write(measure);
}
catch (Exception ex)
{
Log.e("Files", "Error while opening to write file measures.txt");
}
finally
{
try
{
fout.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I guess this part opens the file "measure.txt" in the APPEND mode, or creates it in APPEND mode.
When I try to read from it:
BufferedReader fin = null;
try
{
fin = new BufferedReader(new InputStreamReader(context.openFileInput("medidas.txt")));
String line = fin.readLine();
// Some staff with this line
fin.close()
}
// catch staff
What I want to do is delete all the content in the text file before I close the file. The idea is store the information in another type of variable, and then, when I finish reading from file, reset the content.
How can I do that?
Ok, I solved my problem doing this:
deleteFile("measures.txt");
And that will [i]erase[/i] for sure the file... :P

Reading int value from txt file on SD card android

So in this app I made, The user makes a project and when they save, the number of frames is saved to numberFrames.txt on the SD card. Then I retrieve the file in another class. Only thing is that nFrames = 50 when i show a toast of nFrames to the screen after I run this code. The only initializing of nFrames I do is to zero right above this code, which is located in the onCreate().
File sdcardLocal = Environment.getExternalStorageDirectory();
File dir = new File (sdcardLocal.getAbsolutePath() + "/Flipbook/"+customizeDialog.getTitle()+"/");
dir.mkdirs();
File fileNum = new File(dir, "numberFrames.txt");
FileWriter myFileWriter = null;
try {
myFileWriter = new FileWriter(fileNum);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = new BufferedWriter(myFileWriter);
try {
String text = bitmaps.size()+"";
out.write(text);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
I retrieve the file like this. I have no idea where this "50" value for nFrames came from as there are no loops around this and I know for sure that the particular project saved has only 3 frames. Why is this?
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(mFolderDialog.getPath()+"/numberFrames.txt"));
bis = new BufferedInputStream(is);
nFrames = bis.read();
}catch (IOException e) {
e.printStackTrace();
}
You are writing out a string, and then reading the first byte as an integer. 50 is the ascii code for the '2' character.
You can use BufferedReader.readLine to read the entire first line of the file as a String, and then Integer.parseInt to convert that to an integer.
Also, I would take a closer look at your application's workflow. You don't give much information, but saving a file with a single integer value to the sdcard has a certain "smell" to it :). Have you looked at using a database, or maybe store the text file in your application's directory instead?

write and read strings to/from internal file

I see a lot of examples how to write String objects like that:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
but not how to read them back from internal application file. Most of examples assume specific string length to calculate byte buffer but I do not know what the length will be. Is there an easy way to do so? My app will write up to 50-100 strings to the file
Writing strings this way doesn't put any sort of delimiters in the file. You don't know where one string ends and the next starts. That's why you must specify the length of the strings when reading them back.
You can use DataOutputStream.writeUTF() and DataInputStream.readUTF() instead as these methods put the length of the strings in the file and read back the right number of characters automatically.
In an Android Context you could do something like this:
try {
// Write 20 Strings
DataOutputStream out =
new DataOutputStream(openFileOutput(FILENAME, Context.MODE_PRIVATE));
for (int i=0; i<20; i++) {
out.writeUTF(Integer.toString(i));
}
out.close();
// Read them back
DataInputStream in = new DataInputStream(openFileInput(FILENAME));
try {
for (;;) {
Log.i("Data Input Sample", in.readUTF());
}
} catch (EOFException e) {
Log.i("Data Input Sample", "End of file reached");
}
in.close();
} catch (IOException e) {
Log.i("Data Input Sample", "I/O Error");
}

Categories

Resources