I use the following code to save password in a txt file:
String FILE_NAME="lol.txt";
public void writeData(String password){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(password);
osw.close();
fOut.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
}
but When I retrive the password that I just Saved using toast its appears OK, but when I Log it into my LogCat I got Something like the following:
gana???????????????????????????????????? .... and more four lines.
I save the word gana into my file using save method which work as OnClikc method that set value of EditText as password as below:
public void save(View v){
password= txt.getText().toString();
writeData(password);
}
any Way or clue how can I solve this problem?
regards
Use below code to reading file
byte[] b = null;
try
{
//read file data...
FileInputStream myFile = openFileInput("lol.txt");
b = new byte[1024];
myFile.read(b);
Log.i("Pass", "File data is: " + new String(b).trim());
myFile.close();
}
catch (IOException e)
{
}
only difference with your code is that i am using new String(b).trim() to remove blank space.
Related
Could someone look at this snippet of code please and let me know what I'm doing wrong? It's a simple function that takes a string as parameter which it uses as a file name, adding ".txt" to the end of it.
The function checks if the file exists, creating it if it doesn't and then writes two lines of text to the file. Everything appears to be working and the file is created successfully on the sd card. However, after everything is done, the file is empty (and has a size of 0 bytes).
I suspect it's something obvious that I'm overlooking.
public void writeFile(String fileName) {
String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
myPath.mkdirs();
File file = new File(myPath, fileName+".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
return;
}
}
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
// Do whatever
}
}
Hi I will show you the full code I use, works perfect.
I don't use
new OutputStreamWriter()
i use
new BufferedWriter()
here is my Snippet
public void writeToFile(Context context, String fileName, String data) {
Writer mwriter;
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");
if (!dir.isDirectory()) {
dir.mkdir();
}
try {
if (!dir.isDirectory()) {
throw new IOException(
"Unable to create directory myFolder. SD card mounted?");
}
File outputFile = new File(dir, fileName);
mwriter = new BufferedWriter(new FileWriter(outputFile));
mwriter.write(data); // DATA WRITE TO FILE
Toast.makeText(context.getApplicationContext(),
"successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
mwriter.close();
} catch (IOException e) {
Log.w("write log", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
}
}
-- Original Code --
That one took a while to find out. The javadocs
here brought me on the right track.
It says:
Parameters
name The name of the file to open; can not contain path separators.
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
The file is created, if it does not exist, but it is created in the private app space. You create the file somewhere on the sd card using File.createNewFile() but when you do context.openFileOutput() it creates always a private file in the private App space.
EDIT: Here's my code. I've expanded your method by writing and reading the lines and print what I got to logcat.
<pre>
public void writeFile(String fileName) {
try {
OutputStreamWriter writer = new OutputStreamWriter(
getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
// Now read the file
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(
getContext().openFileInput(fileName + ".txt")));
for(String line = is.readLine(); line != null; line = is.readLine())
Log.d("STACKOVERFLOW", line);
is.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
}
Change the mode from Context.MODE_PRIVATE to Context.MODE_APPEND in openFileOutput()
MODE_APPEND
MODE_PRIVATE
Instead of
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
Use
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
UPDATE :
1.
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
OutputStreamWriter writer = new OutputStreamWriter(osr);
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write("First line");
fbw.newLine();
fbw.write("Second line");
fbw.newLine();
fbw.close();
Or 2.
private void writeFileToInternalStorage() {
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
String eol = System.getProperty("line.separator");
BufferedWriter fbw = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(osr);
fbw = new BufferedWriter(writer);
fbw.write("First line" + eol);
fbw.write("Second line" + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fbw != null) {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i created a file and when i run the program, the data is been written in to the file but when i run the program again the new data over write on old data.
i need once the program is running and gathers data, these data are writable into the file in cascade next each other without overwriting on previous data in file.
this code running successful but when i run the program again the over writing happens which i don need that, i need to save previous data in side the file and write the new data next it and soon.
after edit this code its looks like:
public class MainActivity extends Activity {
File file;
File sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FileName = "Output3.txt";
String eol;
OutputStream fos1;
FileWriter fw ;
BufferedWriter writer;
BufferedWriter bw ;
PrintWriter out;
EditText txtData;
Button btnWriteSDFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sdCard =getExternalFilesDir(null);
file = new File(sdCard,FileName);
txtData = (EditText) findViewById(R.id.editText1);
btnWriteSDFile = (Button) findViewById(R.id.button1);
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
fos = new FileOutputStream(file);
myOutWriter =new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
please,can any one answer me?
Instead of using OutputStreamWriter use Filewriter FileWriter fileWritter = new FileWriter(file,true); when u pass true it appends the contents.try this
FileWriter myOutWriter = new FileWriter(file.getName(),true);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.write(txtData.getText() + eol);// write this text.
writer.close();
fos.close();
Change this line:
fos = new FileOutputStream(file);
To:
fos = new FileOutputStream(file, true);
This opens the file so that data can be appended.
JavaDocs for FileOutputStream
use
FileWriter writer = new FileWriter("yourfilename", true);
second parameter should be passed as true which will append data instead of overwriting
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
// this changed bye fos = new FileOutputStream(myFile) to
fos = new FileOutputStream(myFile,true);
//FileWriter writer = new FileWriter("yourfilename", true);
myOutWriter = new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append("\n");
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),
"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT)
.show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Enjoye i have tested it is work for me.
I am wanting to pass the data added into these fields to a .txt file stored on the device.
Try to do something as I show below:
Button btn11 = (Button) this.findViewById(R.id.buttonformdata);
btn11.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
FileOutputStream fos = openFileOutput("yourFile", Context.MODE_PRIVATE);
String string1 = editText1.getText().toString();
String string2 = editText2.getText().toString();
String string3 = editText3.getText().toString();
fos.write(string1.getBytes());
fos.write(string2.getBytes());
fos.write(string3.getBytes());
fos.close();
}catch(Exception e){
Log.e("Exception", e.toString());
}
}
});
Let me know if it works!
In your xml file you can add android:onClick="bSomething" to the properties of the button you want to click. Then on your activity class (or where you have your code that you posted) you can do something like:
public void bSomething(View view){
try{
FileOutputStream fout = openFileOutput(“yourfile.txt”,MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(editText1.getText().toString()+" ");
osw.write(editText2.getText().toString()+" ");
osw.write(editText3.getText().toString()+" ");
osw.close();
fout.close();
}catch(Exception e){
//do the exception handling
}
}
Hope that helps.
I'm creating a class to manage text files. I have a method to write and an other to read my file :
public static void writeFiles(Context context, String nomFichier, String content, char mode) {
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
if (mode == 'd') {
context.deleteFile(nomFichier);
} else {
fOut = context.openFileOutput(nomFichier, Context.MODE_APPEND);
osw = new OutputStreamWriter(fOut);
osw.write(content);
osw.flush();
}
} catch (Exception e) {
Toast.makeText(context, "Message not saved",Toast.LENGTH_SHORT).show();
} finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
Toast.makeText(context, "Message not saved",Toast.LENGTH_SHORT).show();
}
}
}
When I create a file, it is filled with few empty lines. I want to set the content of my file into an EditText, so I don't want the blanks.
How can I create a file without blanks?
Thx, korax.
EDIT :
I use trim(), suggested by appserv and acj, but in the read function instead of write function. It works fine, thx you!
public static String readFile(Context context, String fileName) {
FileInputStream fIn = null;
InputStreamReader isr = null;
char[] inputBuffer = new char[255];
String content = null;
try {
fIn = context.openFileInput(fileName);
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
content = new String(inputBuffer);
} catch (Exception e) {
//Toast.makeText(context, "Message not read",Toast.LENGTH_SHORT).show();
}
finally {
try {
isr.close();
fIn.close();
} catch (IOException e) {
//Toast.makeText(context, "Message not read",Toast.LENGTH_SHORT).show();
}
}
return content.trim();
}
If you are using a text editor to create the file, the editor may be adding some blank lines to pad the file size. You could call openFileOutput without the MODE_APPEND flag to create the new (empty) file programmatically, thus avoiding the text editor.
Otherwise, appserv's suggestion to use trim() should work nicely to clean up the string.
I am writing to file in android and read from the same file using the below code:
//Write data on file
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = openFileOutput("gasettings.dat", MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, "Settings saved", Toast.LENGTH_SHORT)
.show();
}
catch (Exception e) {
e.printStackTrace();
}
and the code for reading from file is:
InputStreamReader isr = null;
fileInputStream fIn = null;
char[] inputBuffer = new char[255];
String data = null;
try {
fIn = openFileInput("gasettings.dat");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
}
catch (Exception e) {
e.printStackTrace();
}
as per now I am only able to save a string to this file.
I like to write a DATE array to it and also want to read back the data as array.
I know that the return type of read method will be changed, but I am not getting the idea of how to read and write the DATE array or any other array to the file.
Thanks
In that case, your better choice is using JSON. It will allow you to save an array in String format, read it back and convert it again into the original array.
Take a look of this example: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/