Android adding multiple lines to file internal stroage - java

I have a simple game app that has 3 place scoreboard and I need to save the data. I'm not sure whether I should be saving this on external or internal storage. I have managed to save a csv file in external but when testing I found it deosnt work on all devices. I am now looking at saving the data on internal storage and looking at the following standard file saving code.
String FILE_NAME = "file.txt";
try {
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(someText.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
The class doesnt provide any nextLine() method.
My question is should I use external or internal storage, and if im using internal storage how can I seperate each line?

Writing:
String FILE_NAME = "file.txt";
try {
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
PrintWriter writer = new PrintWriter( new OutputStreamWriter( fos ) );
writer.println(someText.toString());
writer.println(someOtherText.toString());
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
Reading:
String FILE_NAME = "file.txt";
try {
FileInputStream fis = openFileInput(FILE_NAME, Context.MODE_PRIVATE);
BufferedReader reader = new BufferedReader( new InputStreamReader( fis ) );
String line;
while ( (line = reader.readLine()) != null ) {
System.out.println("Read line: " + line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}

Related

Can not read any text file

First of all, I would like you to say that I am quite new here and I'm also a beginner in Android Studio and Java.
My problem/question is:
I have an App in Android Studio which should write a string to a text file at a specific point and also should read the same file on App startup.
Writing to the file is working but not reading. When I create a text file manually, and insert it manually to the folder it reads the string.
I already added permissions and try to find my error with LogCat but I have no clue at the moment what could be wrong.
Variables:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/myApp");
My reading function:
String myData = "";
try {
FileReader fileIn = new FileReader(dir + "/data.txt");
Scanner input = new Scanner(fileIn);
while (input.hasNextLine()) {
String line = input.nextLine();
myData = myData + line;
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
My writing function:
try {
File file = new File(dir, "data.txt");
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("answer42");
pw.flush();
pw.close();
f.close();
} catch (Exception ex) {
ex.printStackTrace();
}

How to read binary files in a string sequence of 1 and 0?

I've created a Huffman coding algorithm, and then I wrote binary code in String and put it in binary file using FileOutputStream and DataOutputStream.
But now I cant understand how to read it? I need to get 1 and 0 sequence from binary file.
There is no method like .readString() in DataInputStream
try{
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary", "*.bin"));
FileOutputStream fileOutputStream = new FileOutputStream(fileChooser.showSaveDialog(window));
DataOutputStream outputStream = new DataOutputStream(fileOutputStream);
outputStream.writeChars(Main.string_ready_encode);
}catch (IOException e){
e.printStackTrace();
}
Main.string_ready_encode contains ready sequence
The problem with your writing code is that you have specified no file format. We now can only read the file if we know how many bytes it has. If you do know that, you can read it by doing the following:
try (DataInputStream stream = new DataInputStream(new FileInputStream(f))) {
byte[] bytes = new byte[NUMBER_OF_BYTES];
stream.read(bytes);
String content = new String(bytes);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
But I would actually advise you to rewrite you file with some known file format, like so:
try (Writer writer = new OutputStreamWriter(new FileOutputStream(f), Charsets.UTF_8)) {
writer.write(Main.stringReadyEncode, 0, Main.stringReadyEncode.length());
} catch (IOException x) {
e.printStackTrace();
}
And read it like you would read any other file:
try (BufferedReader r = Files.newBufferedReader(f.toPath(), Charsets.UTF_8)) {
String line;
while((line = r.readLine()) != null) {
// do whatever you want with line
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Just make sure to replace Charsets.UTF_8 with whatever encoding you used while writing to the file.

Editing a file using FileWriter

I am trying to Edit a existing file which is in my R.raw folder
i am able to read the file
but when i run the write function it is not working .
public void tofile(View v){
BufferedWriter bw=null;
FileWriter fw =null;
try {
String path = ("/Page2/res/raw/text.txt");
File file = new File(path);
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write("hello");
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
i even tried
fw = new FileWriter(file,true);
if i add toast between even line it seems to get stuck at
fw = new FileWriter(fw);
You can't able to Write
As #CommonsWare said you can't write on resources but you could use internal storage using openFileOutput and openFileInput and BufferedReaders and BufferedWriters. You can check it here
from the answer of #rodkarom in the following link
Write to a Text File Resource in Android
and #Andro Selva says same thing in the following link
How to write a file in Android to the raw folder?
you can able to read the content from the textfile which is present in the res/raw folder dude
read the file from res folder
public String readStringFromResource(Context ctx, int resourceID) {
StringBuilder contents = new StringBuilder();
String sep = System.getProperty("line.separator");
try {
InputStream is = ctx.getResources().openRawResource(R.raw.trails);
BufferedReader input = new BufferedReader(new InputStreamReader(is), 1024*8);
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(sep);
}
}
finally {
input.close();
}
}
catch (FileNotFoundException ex) {
Log.e(TAG, "Couldn't find the file " + resourceID + " " + ex);
return null;
}
catch (IOException ex){
Log.e(TAG, "Error reading file " + resourceID + " " + ex);
return null;
}
return contents.toString();
}
check it and inform

Saving String Input on Android

Right, I've been trying to find a solution to this for a good while, but it's just not working for some reason.
In short, what I want to do is save every input String the user inputs into a file. Every time the activity is created again, I want to re-input these strings into a new instance of an object.
This code is what I use to create the file and read info from it, used in the onCreate() method of activity
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
String s; // This feeds the object MegaAndroid with the strings, sequentially
while ((s = in.readLine()) != null) {
MegaAndroid.add(s);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
After that, every time the user inputs some text, the strings are saved onto the file:
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(message); // message is a string that holds the user input
out.close();
} catch (IOException e) {
e.printStackTrace();
}
For some reason, however, every time the application is killed, the data is lost.
What am I doing wrong?
EDIT: Also, if I were to access this file from another class, how can I?
As we discussed in the commend section the chief problem with the code is that your execution of FileWriter occurred prior to your FileReader operation while truncating the file. For you to maintain the file contents you want to set the write operation to an append:
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(message);
out.newLine();
out.close();
However, if every entry on the EditText is received then shipped into the file you'll just be writing data byte after byte beside it. It is easy to get contents similar to
This is line #1This is line #2
Instead of the desired
This is line #1
This is line #2
which would be corrected by having the BufferedWriter pass a newline after each write to the file.
This is what I do for file reading.
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
Log.d(TAG,"path: "+dir.getAbsolutePath());
File file = new File(dir, "VERSION_FILENAME");
FileInputStream f = new FileInputStream(file);
//FileInputStream fis = context.openFileInput(VERSION_FILENAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
Log.d(TAG,"first line versions: "+line);
while(line != null){
Log.d(TAG,"line: "+line);
//Process line how you need
line = reader.readLine();
}
reader.close();
f.close();
}
catch(Exception e){
Log.e(TAG,"Error retrieving cached data.");
}
And the following for writing
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
File file = new File(dir, "CONTENT_FILENAME");
FileOutputStream f = new FileOutputStream(file);
//FileOutputStream fos = context.openFileOutput(CONTENT_FILENAME, Context.MODE_PRIVATE);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));
Set<String> keys = Content.keySet();
for(String key : keys){
String data = Content.get(key);
Log.d(TAG,"Writing: "+key+","+data);
writer.write(data);
writer.newLine();
}
writer.close();
f.close();
}
catch(Exception e){
e.printStackTrace();
Log.e(TAG,"Error writing cached data.");
}
You can use the private mode if you don't want the rest of the world to be able to see your files, but it is often useful to see them when debugging.

Internal Storage android -Device memory

Can some one help me explain how to read and display the data stored in the Internal Storage-private data on the device memory.
String input=(inputBox.getText().toString());
String FILENAME = "hello_file"; //this is my file name
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(input.getBytes()); //input is got from on click button
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos1= openFileInput (FILENAME);
} catch (FileNotFoundException e) {}
outputView.setText(fos1./*I don't know what goes here*/);
openFileInput returns a FileInputStream object. Then, you will have to read the data from it using the read methods it provides.
// missing part...
int len = 0, ch;
StringBuffer string = new StringBuffer();
// read the file char by char
while( (ch = fin.read()) != -1)
string.append((char)ch);
fos1.close();
outputView.setText(string);
Take a look at FileInputStream for further reference. Keep in mind that this will work fine for text files... if it's a binary file it will dump weird data into your widget.
There are a lot of ways to read in the text, but using a scanner object is one of the easiest ways for me.
String input=(inputBox.getText().toString());
String FILENAME = "hello_file"; //this is my file name
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(input.getBytes()); //input is got from on click button
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String result = "";
try {
fos1= openFileInput (FILENAME);
Scanner sc = new Scanner(fos1);
while(sc.hasNextLine()) {
result += sc.nextLine();
}
} catch (FileNotFoundException e) {}
outputView.setText(result);
You need to import java.util.Scanner; for this to work. The Scanner object has other methods too like nextInt() if you want to get more specific information out of the file.

Categories