Reading Text file in android - java

I am trying to read a text file stored in my mobile device external storage , but it is throwing this error: -
Error occured while reading text file!!/storage/emulated/0/atom.txt: open failed: ENOENT (No such file or directory)
Here's the code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.btn_picker);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
fileOpener();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void fileOpener() throws IOException {
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"atom.txt");
//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);
text.append('\n');
}
}
catch (IOException e) {
Log.e("Error", "Error occured while reading text file!!" + e.getMessage());
}
//Find the view by its id
Log.d("Text",text.toString());
}
}
How can I figure this out?
EDIT : The atom.txt file is already saved in my device but still it is throwing the same error.

The file doesn't exist, so the path returned by Environment.getExternalStorageDirectory is not what you are expecting it to be. According to the API docs, this path is not guaranteed to be an SD card.

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 play Audio from internal storage with encoded string file

I want to play a decoded string to audio file.
The string is received from another activity, but mediaPlayer shows null. How can I get and set the path in media.create()?
public class AAudio extends AppCompatActivity {
Button play_audio;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aaudio);
String recieve_file = getIntent().getStringExtra("audio_file");
play_audio = findViewById(R.id.textShow);
byte[] decoded = Base64.decode(recieve_file, 0);
String fileName = String.valueOf(decoded);
Log.e("~~~~~~~~ Decoded: ", Arrays.toString(decoded));
try {
String root = Environment.getExternalStorageDirectory().getPath();
File myDir = new File(root, "/kaushlya/mp3");
String path = String.valueOf(myDir);
myDir.mkdirs();
String audioName = "Advicory.mp3";
File file = new File(myDir, audioName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file, true);
os.write(decoded);
os.close();
**mediaPlayer = MediaPlayer.create(this, Uri.parse(Uri.parse(root)+path+fileName));
mediaPlayer.setLooping(true);**
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
play_audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}

Find words in text file from assets folder ANDROID STUDIO

I have a problem with my app.
What I'm trying to do is to find rhymes to a word entered from the user into a text field.
I have a dictionary in assets folder called "words.txt".
My app is working almost correctly, but it finds only one word from my text file.
How can I find all words that rhyme with the word from the text field?
Any ideas?
Here is my code:
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
editTextWord = (EditText)findViewById(R.id.editTextWord);
b_read = (Button)findViewById(R.id.buttonSearch);
tv_text = (TextView)findViewById(R.id.nameTxt);
b_clear = (Button)findViewById(R.id.buttonClear);
b_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
}
});
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
InputStream is = getAssets().open("words.txt");
int size = is.available();
BufferedReader rd = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String line;
String word = editTextWord.getText().toString();
if (word.isEmpty()){
Toast.makeText(getApplicationContext(), "Wpisz słowo", Toast.LENGTH_SHORT).show();
return;
}
while ((line = rd.readLine()) !=null ){
if (line.substring(line.length()-2).equals(word.substring(word.length()-2))){
tv_text.setText(line);
}
}
rd.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
});
}
tv_text.setText overwrites anything that is already in the TextView. You need to use something like TextView.append(CharSequence)
Try:
tv_text.append(line + "\n");

How to change file name in edittext

I found some interesting codes online. And I copy paste it into my AIDE or Android IDE. It hasn't detected any error so far but it just only saves in one file name in all files I saved. And the older file saved will be replaced by a newer one.
public class MainActivity extends Activity {
public EditText editText;
public TextView textView;
public Button save, load;
public String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.edit);
textView = (TextView) findViewById(R.id.text);
save = (Button) findViewById(R.id.save);
File dir = new File(path);
dir.mkdirs();
}
public void buttonSave (View view)
{
File file = new File (path + "/saved.txt");
String [] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save (file, saveText);
}
}
public static void Save(File file, String[] data)
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(file);
}
catch (FileNotFoundException e) {e.printStackTrace();}
try
{
try
{
for (int i = 0; i<data.length; i++)
{
fos.write(data[i].getBytes());
if (i < data.length-1)
{
fos.write("\n".getBytes());
}
}
}
catch (IOException e) {e.printStackTrace();}
}
finally
{
try
{
fos.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
I am planning to make an edittext and name it as yourfilename and that will be its name after I saved it to prevent overwriting files. But the problem is I don't know where to add codes and for so many codes there. I am having doubt of which codes to be used.
By the way, I am very new to this so I do not know much about it.
Thank you.
Check if this helps you.
public void buttonSave(View view) {
String fileName = editText.getText().toString();
File file = new File(path + "/" + fileName + ".txt");
String[] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save(file, saveText);
}

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();
}

Categories

Resources