saving a text in the notepad in android - java

I just want to ask about my code whether it's right, because I can't load the text in my name.txt file.
Also I just want to know how to save the input text in my name.txt file.
load.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick
(View arg0) {
try{
StringBuffer sb=new StringBuffer();
FileInputStream fis=con.openFileInput("name.txt");
DataInputStream dis=new DataInputStream(fis);
String text=null;
while((text=dis.readLine())!=null)
sb.append(text+"\n");
dis.close();
et1.setText(sb.toString());
}catch
(IOException e){
Toast.makeText(con, "Could not find", Toast.LENGTH_LONG).show();
}
}
});

If you want to write data to file
static protected void writeToFile(String strToWrite)
{
try
{
BufferedWriter out = new BufferedWriter(new FileWriter("name.txt", true));
out.write(strToWrite);
out.close();
}
catch (IOException e) { e.printStackTrace();}
}
The code you have written is to read data from an existing file not to write in the file.

try
{
File file1 = new File(Environment.getExternalStorageDirectory() + "/dir/", "filename.extension");
FileWriter fw1 = new FileWriter(file1.getAbsoluteFile());
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write("Stringtowritetofile");
bw1.close();
}

Related

AndroidStudio - save user info in CSV file and read it

I'm a newbie in programming on Android Studio. I'm trying to create a simple application to gain basic experience. In the application, I would need to store individual inputs to a file (ideally CSV) in internal memory. First of all, I am trying to save user data - my name and phone number. The save method looks like this:
public void save(View view)
{
String fileName = "user.csv";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
File file = new File(directory, fileName);
String data = "FirstName,LastName,PhoneNumber";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
The data seems to be saved and I'm redirected to MainActivity. Here is the method:
protected void onCreate(Bundle savedInstanceState) {
File file = new File(getFilesDir(),"user.csv");
if(!file.exists()) {
Intent intent = new Intent(this, activity_login.class);
startActivity(intent);
}
else {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_name = findViewById(R.id.tv_name);
TextView tv_phone = findViewById(R.id.tv_phone);
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("user.csv"));
while ((sCurrentLine = br.readLine()) != null) {
tv_name.setText(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
No value is stored in TextView tv_name and the box is empty. Where am I making mistake?
Thank you very much for your help!
For reading data saved use this method uses, UTF_8 ENCODING
public static String readAsString(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
String line;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
reader = new BufferedReader(new InputStreamReader(is,UTF_8));
}
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
return sb.toString();
}
Use this method as follows, parsing file "user.csv".
public static String readFileAsString(File file) throws IOException {
return readAsString(new FileInputStream(file));
}
Fetch string and set textView
Use as this to read file:
FileInputStream fis = new FileInputStream("your full file path");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
Below is the code for creating .csv file and inserting data into it.
For more look into my answer :https://stackoverflow.com/a/48643905/8448886
CODE HERE:
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});

How to remove specific line from the file

I am trying to delete a specific line from a file, but when I run this, it returns me all the files, deleted. More specific i have a favorite button at a video fragment and i want when user press it ,to write the title of video in file (already done) and when unpress it to delete it....
my.java class is:
private void writeToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/config.txt");
FileOutputStream fos = new FileOutputStream(file,true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (!file.exists()) {outputStreamWriter.write(g);}
outputStreamWriter.append("\n"+g +"\n");
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private void deleteToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
outputStreamWriter.write(text.toString());
}
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.favorite:
if(showingFirst==true) {
Context context = getActivity();
CharSequence text = "Added to Favorites";
int duration = Toast.LENGTH_SHORT;
item.setIcon(R.drawable.heart_off);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
writeToFile(title,context);
showingFirst=false;
} else {
Context context = getActivity();
CharSequence text = "Deleted from Favorites";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
deleteToFile(title,context);
item.setIcon(R.drawable.heart_wh);
showingFirst=true;
}
break;
case R.id.home:
Intent k=new Intent(getActivity(),MainActivity.class);
Log.i(TAG, "onNavigationItemSelected: ");
startActivity(k);
break;
}
return false;
}
So, problem lies at below line of codes where you are trying to open file for Read and Write simultaneously
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
Instead, I would suggest you to read your file completely and then at the end you should write to the file (overwrite).
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
//start writing from here
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
outputStreamWriter.write(text.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
}
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
This line:
FileOutputStream fos = new FileOutputStream(file);
resets contents of the file (ie replaces it with empty file). I recommend you add logging and/or debug your code so you will have a better understanding of what is going on.

How to read text file upon opening an app?

I am making an app where I have my school balance set and can press dedicated buttons to take away certain amounts depending on what I purchase. I am having trouble with the balance. I have a way of updating it to what I want, however after I terminate the application I want it to stay the same in a TextView. I so far was able to make it save it to a file, or at least I hope I was, with the help of a video.
How could I on opening the app read the text file and set the TextView equal to what is in the file?
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String submitAmount = amountEnter.getText().toString();
balance.setText(submitAmount);
String myBalance = balance.getText().toString();
try {
FileOutputStream fou = openFileOutput("balance.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fou);
try {
osw.write(myBalance);
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
You can save it in SharedPrefs
change it to
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String submitAmount = amountEnter.getText().toString();
balance.setText(submitAmount);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
edit().putString("balance", submitAmount).commit();
}
});
and you can get it by
String balance=PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getString("balance","nothing_there");
Seeing your code, i assume that you know how to read/write a file in android. If not, then see it from here . https://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android/ You can try the following code. THe readfile method is from the upper link. You just have to read the particular line/string from the file at onCreate method of the activity. Get the reference of your desired TextView and then set the text to TextView like below. I hope it helps you
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
String texts = readfile();
TextView textView = findViewById(R.id.text_view);
textView.setText(text);
}
private String readfile() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "file.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
return text.toString();
}

android.content.res.Resources$NotFoundException

hey I have a problem with loading data from a txt file
private void read() {
try {
// open the file for reading
InputStream instream = openFileInput(File.separator + "bla.txt");
// if file the available for reading
if (instream.available() >0) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine()) != null) {
for(int i= 0; i<=1; i++){
if(i == 0){
bla = Integer.parseInt(buffreader.readLine());
}
if(i == 1){
bla2 = Integer.parseInt(buffreader.readLine());
}
}
// close the file again
instream.close();
Toast.makeText(getBaseContext(),
"Ladevorgang war efolgreich!",
Toast.LENGTH_LONG).show();
}}
}
catch (java.io.FileNotFoundException e) {
Toast.makeText(getBaseContext(),
"Datei nicht vorhanden",
Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
Please help me I dont know what I should change:(
I alway got the android.content.res.Resources$NotFoundException: String resource ID #0x0
Thanks for help Strik3r
private void save() {
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
this is the save data
// open the file for reading
InputStream instream = openFileInput(File.separator + "bla.txt");
does not seem to be a valid file.
Instead, please try
InputStream instream = openFileInput(Environment.getExternalStorageDirectory() +File.separator + "bla.txt");

android: FileOutputStream Doesn't work

I try to make TCP-Sock program, and this is simple file recv program.
and now, i get some problem.
i think my client program's FileOutputStream class doesn't work.
below code is what i've made.
package kr.ac.cbnu.incping.tcp_cloud;
public class DownActivity extends Activity {
public static int contentNum;
public static String body=new String();
public static String fName=new String();
public static int fSize;
public static synchronized String getFilePath(String userID, String fName)
{
String sdcard = Environment.getExternalStorageState();
File file = null;
if ( !sdcard.equals(Environment.MEDIA_MOUNTED))
{
// SDcard isn't mount
file = Environment.getRootDirectory();
}
else
{
// SDcard is mount
file = Environment.getExternalStorageDirectory();
}
String dir = file.getAbsolutePath() + String.format("/tcp_cloud/%s",userID);
String path = file.getAbsolutePath() + String.format("/tcp_cloud/%s/%s",userID,fName);
file = new File(dir);
if ( !file.exists() )
{
// Make directory if dir doesn't exist
file.mkdirs();
}
// return File Path;
return path;
}
public void connect()
{
try{
Socket socket=new Socket(MainActivity.servIP, MainActivity.servPort);
DataOutputStream dos;
DataInputStream dis;
dis=new DataInputStream(socket.getInputStream());
dos=new DataOutputStream(socket.getOutputStream());
byte[]flag=new byte[3];
byte[]num=new byte[1];
byte[]uID=new byte[17];
String path=new String();
path=getFilePath(LoginActivity.usrName,fName);
File f=new File(path);
flag="05".getBytes("EUC_KR");
num=Integer.toHexString(contentNum).getBytes("EUC_KR");
uID=LoginActivity.usrName.getBytes("EUC_KR");
dos.write(flag);
dos.flush();
dos.write(num);
dos.flush();
dos.write(uID);
dos.flush();
FileOutputStream fos=new FileOutputStream(f);
Toast.makeText(getApplicationContext(),path,Toast.LENGTH_LONG).show();
BufferedOutputStream bos=new BufferedOutputStream(fos);
dos=new DataOutputStream(bos);
int len;
int size = 512;
byte[] data = new byte[size];
while ((len = dis.read(data,0,size))!=-1)
{
dos.write(data);
}
dos.flush();
Toast.makeText(getApplicationContext(),path+" saved",Toast.LENGTH_LONG).show();
dos.close();
bos.close();
fos.close();
dos.close();
dis.close();
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_down);
String title=new String();
if(contentNum==0)
title=LoginActivity.title1;
else if(contentNum==1)
title=LoginActivity.title2;
else if(contentNum==2)
title=LoginActivity.title3;
else if(contentNum==3)
title=LoginActivity.title4;
else if(contentNum==4)
title=LoginActivity.title5;
TextView bodytit=(TextView) findViewById(R.id.bodyTitle);
TextView bodydat=(TextView) findViewById(R.id.bodyBody);
Button filedat=(Button) findViewById(R.id.filename);
bodytit.setText(title);
bodydat.setText(body);
filedat.setText(fName+"(size: "+fSize+")");
filedat.setOnClickListener(new OnClickListener(){
public void onClick(View v){
connect();
}
});
}}
and this code is troubled code
FileOutputStream fos=new FileOutputStream(f);
Toast.makeText(getApplicationContext(),path,Toast.LENGTH_LONG).show();
BufferedOutputStream bos=new BufferedOutputStream(fos);
dos=new DataOutputStream(bos);
toast message is just prob message. when placed toast above of the FOS, toast working well.
but toast isn't working in that position
i can't solve this problem. please, somebody help me..T.T
*i'm not english language area's person. so my english isn't nice sentence. i'm sorry about that;)
In my case FileOutputStream and OutputStreamWriter is not works.
So I was changed File classes to this.
FileWriter fileOut = new FileWriter(fileFullPath, false);
String jsonString = new Gson().toJson(json);
fileOut.write(jsonString);
fileOut.close();

Categories

Resources