Hi I have same problem by Writing String ArrayList to file and Reading.
This is my code for writing
File SettingsPath = getFilesDir();
String strSettingsPath = SettingsPath.toString() + "/settings.txt";
File file = new File (strSettingsPath);
if (!file.exists()) {
File removeFile = new File(strSettingsPath.toString());
boolean deleted = removeFile.delete();
}
try {
FileOutputStream fos =
new FileOutputStream(
new File(strSettingsPath));
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this.strSettings);
os.close();
Log.v("","File has been written");
} catch(Exception ex) {
ex.printStackTrace();
}
And this is for Reading
public void reader(View v) throws FileNotFoundException {
File SettingsPath = getFilesDir();
String strSettingsPath = SettingsPath.toString() + "/settings.txt";
List<String> Settings = new ArrayList<String>();
BufferedReader readerL = new BufferedReader(new FileReader(strSettingsPath));
String line;
try{
//line = readerL.readLine();
while ((line = readerL.readLine()) != null) {
Settings.add(line);
System.out.println("The Setting line is " + Settings);
}
readerL.close();
}catch (IOException e){
e.printStackTrace();
}
By reading I get This
The Setting line is [����sr��java.util.ArrayListx����a���I��sizexp������w������t��]
The Setting line is [����sr��java.util.ArrayListx����a���I��sizexp������w������t��, test#test.comt��passwordt�� itdguccgjx]
and I need like this
test#test.com
password
itdguccgjx
What is wrong?
Sorry for my bad English.
Hi
I will like this.
Textbox1
Textbox2
Textbox3
.......
If I will get value of arraylist.get(1).tostring I get Textbox2
Related
Advance Thanks for your help!
I am searching for this solution for about two days but not solved yet. So, don't mark it as repetitive question.
Here, how I have tried-
Reading file path and setting to EditText: (it's working well)
I have used followings to read the file using that path-
buttond3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File folders = new File(Environment.getExternalStorageDirectory() + "/" + "Information Security"+"/"+"Decrypted Files");
if (!folders.exists()) {
folders.mkdirs();
}
try {
String path= String.valueOf(editTextd2.getText());
String plain = getStringFromFile(path);
String decrypted = Encryption_Decryption2.decrypt(plain, "000102030405060708090A0B0C0D0E0F");
String file_name= String.valueOf(editTextd4.getText());
File f = new File(folders + "/" + file_name);
FileOutputStream fileOutput = new FileOutputStream(f);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutput);
outputStreamWriter.write(decrypted);
outputStreamWriter.flush();
fileOutput.getFD().sync();
outputStreamWriter.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
Here is the getStringFromFile() method-
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
Just problem in reading the file using the path. Please help!!!
i have an editText and I have a button that changes the color ,size and Typeface so when saving the file as pdf or txt file how can i get the this 3 things with the text i'm getting only the text with normal black style this is my code.
size.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtSpeechInput.setTextSize(25);
txtSpeechInput.setTextColor(Color.rgb(150,0,0));
txtSpeechInput.setTypeface(null, Typeface.BOLD);
the save code:
final File externalStorageDir = new File(
Environment
.getExternalStorageDirectory(), "MyVoiceText");
boolean success = true;
if (!externalStorageDir.exists()) {
success = externalStorageDir.mkdirs();
}
if (success) {
final Dialog dialog2 = new Dialog(MainActivity.this);
dialog2.setContentView(R.layout.dialog_save);
dialog2.show();
editsave = (EditText) dialog2.findViewById(R.id.edit_save);
pdf = (Button) dialog2.findViewById(R.id.pdf_save);
pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pdf.setEnabled(false);
txt.setEnabled(true);
}
});
txt = (Button) dialog2.findViewById(R.id.txt_save);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt.setEnabled(false);
pdf.setEnabled(true);
}
});
dia_save = (Button) dialog2.findViewById(R.id.dia_save);
dia_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String savename = editsave.getText().toString();
if(!txt.isEnabled()) {
File myFile = new File(externalStorageDir + "/" + savename + ".txt");
File myFile = new File(externalStorageDir + "/" + savename + ".txt");
try {
StringBuffer string = new StringBuffer();
string.append(txtSpeechInput.getText().toString());
Properties properties = new Properties();
// set the properties value
properties.put("text",string.append(txtSpeechInput.getText().toString())); properties.put("textstyle","bold");
properties.put("typeface",txtstyle);
properties.put("etxtColor",txtcolor);
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(string);
myOutWriter.close();
fOut.flush();
fOut.close();
} catch (Exception e) {
}
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
dialog2.dismiss();
}else if(!pdf.isEnabled()){
try
{
String savename2 = editsave.getText().toString();
String takeit = txtSpeechInput.getText().toString();
Document document = new Document(PageSize.A4);
Paragraph p = new Paragraph();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(Environment.getExternalStorageDirectory() + "/MyVoiceText/" +savename2+".pdf"));
document.open();
writer.getDirectContent();
p.add(new Phrase(takeit));
document.add(p);
document.close();
Log.d("OK", "done");
} catch (Exception e) {
//LOGGER.error(e.getMessage());
}
reload the text file
File sdcard = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyVoiceText/");
//Get the text file
File file = new File(sdcard, String.valueOf(selected));
InputStream input = null;
try {
input = new FileInputStream(file);
Properties prop = new Properties();
// load a properties file
prop.load(input);
}catch (Exception e){
e.printStackTrace();
}
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
catch (IOException e) {
//You'll need to add proper error handling here
}
By your code, it seems like you are using iTextPDF library to generate the PDF.
Use Font class of iTextPDF to create a new font and use it like below:
private static Font HelveticaBlue = new Font(Font.FontFamily.HELVETICA, 6,
Font.BOLD, BaseColor.BLUE);
new Paragraph("Blue ColorText"), HelveticaBlue);
We can add Properties to File that contains entries in key and value format.
And we can write our own Properties in File also retrieve.
like below code:
Write Properties to File:
private void addPropertiesToFile(String mytext){
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/CHETAN");
if (!myDir.exists ())
myDir.mkdirs();
String fname = "mytext.txt";
File myFile = new File (myDir, fname);
if (!myFile.exists ())
myFile.createNewFile();
Properties properties = new Properties();
// set the properties value
properties.put("text","dsf");
properties.put("textstyle","bold");
properties.put("typeface","arial");
properties.put("etxtColor","green");
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.write(mytext);
// save properties to project root folder
properties.store(myOutWriter,null);
myOutWriter.close();
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Retrieve Properties from File:
private void retrievePropertiesFromFile(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/CHETAN");
String fname = "mytext.txt";
File myFile = new File (myDir, fname);
InputStream input = null;
try {
input = new FileInputStream(myFile);
Properties prop = new Properties();
// load a properties file
prop.load(input);
// get the property value and print it out
Log.i(getClass().getSimpleName(),prop.getProperty("text"));
Log.i(getClass().getSimpleName(),prop.getProperty("textstyle"));
Log.i(getClass().getSimpleName(),prop.getProperty("typeface"));
Log.i(getClass().getSimpleName(),prop.getProperty("typeface"));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have a text file is conten.txt which has
101,1,123
102,1,234
I am using Android to update that text file. With a input as "102", I want to update second line with information is "2,234". So it will be
102,2,234
Finally, the content in text file will be
101,1,123
102,2,234
Is it possible to do it in Android? This is my current work. However, tt only writes a new line in the file
String whole_content="102,2,234";
File file = new File(getApplicationContext().getFilesDir(), "conten.txt");
String filepath = Environment.getExternalStorageDirectory().getPath();
FileOutputStream outputStream;
try {
outputStream = openFileOutput("conten.txt", Context.MODE_PRIVATE);
outputStream.write(whole_content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Yes it's possible! Simply, you could create a string of total file content and replace all the occurrence in the string and write that string to that file again.
File log= new File("yourFile");
String search = "102"; //Like you said
try{
FileReader fr = new FileReader(log);
String s;
String totalStr = "";
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
if(s.contain(search)) {
s = search + "," + "yourReplaceString"; //You can extract it from your input
}
totolStr += s;
}
FileWriter fw = new FileWriter(log);
fw.write(totalStr);
fw.close();
}
}catch(Exception e){
e.printStackTrace();
}
I have three strings which write in to list.txt file with this code
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ;
FileOutputStream fop = null;
File file = null;
try {
file =new File(filename);
fop=new FileOutputStream(file,true);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
filecontent=filecontent+ System.getProperty ("line.separator");
// get the content in bytes
byte[] contentInBytes = filecontent.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
The file output detail is
abc.mp3
cde.mp3
edf.mp3
Now, I want to read the detail in list.txt. I used below code but the output only has
cde.mp3
edf.mp3
What is happen with my code? I don't know why data abc.mp3 disappear.
ArrayList<String> data;
try {
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ;
BufferedReader in = new BufferedReader(new FileReader(filename));
String audio_name;
audio_name = in.readLine();
data = new ArrayList<String>();
while ((audio_name = in.readLine()) != null) {
data.add(audio_name);
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
for (int i=0;i<data.size();i++)
{
Log.d("D",String.valueOf(data.get(i)));
}
The first instance of audio_name = in.readLine() would read the first line abc.mp3 but the input is not used. Thus first line read by your while loop and stored in data would be cde.mp3. You should remove the first instance of audio_name = in.readLine().
audio_name = in.readLine();
data = new ArrayList<String>();
You read your first line into your audio_name variable, but you never add it to the list, so that's why it's "missing".
I'm tired messing around.
And i'm beginning to believe that it actually isn't possible.
Where do i find a simple example showing how to write a file "myPath/myFile.txt"?
And then reading it back again?
This an example of a code block that i can't get to work:
if(pathExists(path, ctx))
{
File file = new File(ctx.getFilesDir().getAbsolutePath() +"/" + path, fileName);
FileInputStream fIn = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fIn);
StringWriter writer = new StringWriter();
IOUtils.copy(fIn, writer, "UTF-8");
fileStr = writer.toString();
}
This is the error that i get:
"java.io.IOException: Is a directory"
This following snippet will copy you files which are saved in the application space to your desired path.
File mfile=new File("/data/data/src.com.file.example/files");
File[] list=mfile.listFiles();
// The path where you like to save your files
String extStorageDirectory = "/mnt/sdcard/backup/";
File file23 = null;
File fr = null;
for(int i =0;i<list.length;i++){
File myNewFolder = new File(extStorageDirectory +list[i].getName().substring(0,5));
if(myNewFolder.exists()){
String selectedFilePathq = "data/data/src.com.file.example/file/"+list[i].getName();
file23 = new File(selectedFilePathq);
fr = new File(myNewFolder+"/"+list[i].getName());
}else{
myNewFolder.mkdir();
String selectedFilePathq = "data/data/src.com.file.example/files /"+list[i].getName();
file23 = new File(selectedFilePathq);
fr = new File(myNewFolder+"/"+list[i].getName());
}
try {
copy(file23,fr);
} catch (IOException e) {
e.printStackTrace();
}
}
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
You could not write to Android internal storage (not unless your device is rooted) aside from the private file space assigned to your own application by the android system.
String strfile1 = getApplicationContext().getFilesDir().getAbsolutePath() + "/serstatus.txt" ;
File f1 = new File(strfile1);
you have to use serialization methods as in java.
to save an text as file you should be using FileOutputStream and to read the file you should be using FileInputStream. You can check the following code it has a simple edittext and two buttons one to save and one to read data saved in that file.
The following code is to save text in the file named raksi.
Button savebutton = (Button)findViewById(R.id.but);
savebutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
e= (EditText)findViewById(R.id.edit);
StringBuffer sb = new StringBuffer();
sb.append(e.getText().toString());
String s = sb.toString();
try {
final String TESTSTRING = new String(s);
FileOutputStream fOut = openFileOutput("raksi.txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(TESTSTRING);
ll = TESTSTRING.length();
osw.flush();
osw.close();
}catch (Exception e) {
// TODO: handle exception
}
}
});
The following code is the click listener for the button get. it reads the data from the file and displays as toast,
Button b1 = (Button)findViewById(R.id.but1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
FileInputStream fIn = openFileInput("name.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[ll];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
Toast.makeText(getApplicationContext(), readString, Toast.LENGTH_LONG).show();
}
catch(IOException e){
// TODO: handle exception
}