When I try to read some files in my Android app they appear to not exist, here is my code:
public class ReadFiles1 {
//Static Scanner and File Objects
static Scanner s;
// Static method that returns an ArrayList
static ArrayList<String> words (String filename){
//Instantiate File with file name within parameters
File n = new File(filename);
//Instantiate Scanner s with f variable within parameters
//surround with try and catch to see whether the file was read or not
try {
s = new Scanner(n);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Problem here");
}
//Instantiate a new ArrayList of String type
ArrayList<String> theWord = new ArrayList <String>();
//while it has next ..
while(s.hasNext()){
//Initialise str with word read
String str=s.next();
//add to ArrayList
theWord.add(str);
}
//return ArrayList
return theWord;
}
I don't know what the problem is, I put the txt files in the same package as the .java files.
This is the error I get when runnning this:
check this link for PICTURE(https://ibb.co/cn3QCv)
W/System.err: java.io.FileNotFoundException: build/numbers.txt: open failed: ENOENT (No such file or directory)
Don't put your text files in java folder instead put it in
app/src/main/res/raw/ folder and read it in program using below code.
static ArrayList<String> words (InputStream in) {
try {
s = new Scanner(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Problem here");
}
and call this method from any activity or service using below code
InputStream in = getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);
or if you're calling this method from any other class then should have context reference
InputStream in = context.getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);
Hope this will work.
Related
I am using Android Studio with Java.
I have written a method (namely deleteWithExtension) to delete files from device internal memory. This method is adding some test files and tries to get the listof these files.
But the problem is that, the code never goes in the for-loop because of the array theFiles[] returns null. As you can see that, the code begins with sample files adding process so it should not be empty. I can also see those sample files in the Device File Explorer of Android Studio.
public static void CreateFile(Context mContext, String fileName, String textToBeWritten) {
try {
File dosya = new File(mContext.getFilesDir() + fileName);
dosya.createNewFile();
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write(textToBeWritten);
yazici.flush();
yazici.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void deleteWithExtension(Context mContext, String extension) {
//First let's add a few sample files with same extension.
CreateFile(mContext,"SampleFile1.smp","anything1");
CreateFile(mContext,"SampleFile2.smp","anything2");
CreateFile(mContext,"SampleFile3.smp","anything3");
CreateFile(mContext,"SampleFile4.smp","anything4");
CreateFile(mContext,"SampleFile5.smp","anything5");
//Now, 5 sample files have been added. Let get them and put in an array.
File dir = mContext.getFilesDir();
final String[] theFiles = dir.list();
for (final String file : theFiles) {
//do something here....
int aa=9;
//The code never goes into here, because array theFiles is always null but 5 sample files was added at first.
}
}
replace the CreateFile() method as follows. I hope I can help you.
public static void CreateFile(Context mContext, String fileName, String textToBeWritten) {
try {
File dosya = new File(mContext.getFilesDir() + File.separator + fileName);
dosya.createNewFile();
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write(textToBeWritten);
yazici.flush();
yazici.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I implemented a share button in my app. When I want to share, I can select a saved json data from the device and select via which way I want to share it (mail etc.). The problem is, that the data is NOT in the attachements. The problem is likely because I use the internal app storage. Therefore I want to save tje json data into the external storage, what would be better in my case anyway. But I am not really sure how to do that. I am not sure if I should use the Media type of content of the Documents and other files type of content which is provided by android. There is also the Appspecific files type but this looks like it is not applicaple for me, because I need to share the json data wit ha share functin. At the moment my code looks like this:
Save Function, which get's a file name I can choose myself
private void saveState(String name) {
File file = new File(getFilesDir(), name + ".json");
try{
OutputStream out = new FileOutputStream(file);
MyJsonWriter writer = new MyJsonWriter();
writer.writeJsonStream(out, ... //data structure);
out.close();
}catch (Exception e){
Log.e("saveState ERROR", "----------------------------------------------------");
}
}
LoadButtonClick Functin which shows me all files
public void loadStateClick(View view) {
final LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
String[] files = MainActivity.this.fileList();
... //more code which is not important here
Load Function
private void loadState(String name) {
File file = new File(getFilesDir(), name);
InputStream in = null;
... //setting my data structure, not important here
try{
in = new FileInputStream(file);
MyJsonReader reader = new MyJsonReader(MainActivity.this);
SaveData savedData = reader.readJsonStream(in);
... // handling data structure, not important here
in.close();
}catch (Exception e){
Log.e("LOAD ERROR", e.toString());
}
}
I´m trying to save my values to .csv file with this code.
try {
CSVWriter writer = new CSVWriter(new FileWriter(getFilesDir()+"ECGValues.csv"),',');
// feed in your array (or convert your data to an array)
String[] entries = Values_to_save.toArray(new String[Values_to_save.size()]);
writer.writeNext(entries);
writer.close();
Values_to_save.clear();
Toast.makeText(this,"ECG values saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this,"Error while saving values", Toast.LENGTH_SHORT).show();
Log.e("error", "" + e.getMessage());
Log.e("error",""+ e.getStackTrace());
}
My input data is from
Lead_I_save =String.valueOf(IValue);
Lead_II_save = String.valueOf(IIValue);
Lead_III_save = String.valueOf(IIIValue);
Lead_aVL_save = String.valueOf(aVLValue);
Lead_aVF_save = String.valueOf(aVFValue);
Lead_aVR_save = String.valueOf(aVRValue);
String newLine = String.format("%1$s;%2$s;%3$s;%4$s;%5$s;%6$s;",
Lead_I_save, Lead_II_save, Lead_III_save,
Lead_aVL_save, Lead_aVF_save, Lead_aVR_save);
Values_to_save.add(newLine);
A Toast appears with ECG values saved, but I cannot find the .csv anywhere.
I will welcome any suggestions. Thanks
You used a relative path (only a file name) and then your file lands in the apps private internal memory which is unreachable for other apps. Use a full path to external memory instead.
So I want to save whatever users write in their EditText to be saved for the next time. This exact same code works for java project but with Android project, it doesnt work.
The code is below.
The PrintWriter out = new PrintWriter("hi"); always gives the FileNotFoundException e.
In java project, this code The PrintWriter out = new PrintWriter("hi"); makes a new file with the name "hi" but android project does not produce a new file instead returns the error. It does not save the String from the EditText to be opened when the app opens up again later.
Does anyone have a solution to this problem?
public void onCreate(blablabla)
{blablabla
try {
FileReader reader = new FileReader ("hi");
Scanner in = new Scanner(reader);
String line = in.nextLine();
mEditText.setText(line);
in.close();
} catch (FileNotFoundException e) {
mEditText.setText("");
Toast.makeText(mContext, "null!!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy()
{
super.onDestroy();
// The activity is about to be destroyed.
try {
PrintWriter out = new PrintWriter("hi");
out.write(mEditText.toString());
out.close();
} catch (FileNotFoundException e) {
Toast.makeText(mContext, "Can't save", Toast.LENGTH_SHORT).show();
}
}
May be Android permission problem. See http://developer.android.com/guide/topics/manifest/manifest-intro.html#perms
Or better to use SharedPreferences?
ey up. ive built a simple music app that reads wav files from the sdcard and plays them.
how do i access the default media directory?
this is how i get the sdcard
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
File sd = new File(Environment.getExternalStorageDirectory ()); //this needs to be a folder the user can access, like media
as usual the docs dont give an actual example of usage but it says this - If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC...
how do i use it?
thank you
edit:
this makes it crash if i try to fill a spinner array with file path Strings.
File path = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
File sd = new File(path, "/myFolder");
File[] sdDirList = sd.listFiles(new WavFilter());
if (sdDirList != null)
{
//sort the spinner
amountofiles = sdDirList.length;
array_spinner=new String[amountofiles];
......
final Spinner s = (Spinner) findViewById(R.id.spinner1); //crashes here
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this,
android.R.layout.select_dialog_item, array_spinner);
EDIT2:
ok so ive done this test that is supposed to write a txt file to the music directory.
i run the app, no txt file is written anywhere on the device i can find.
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
String fname = "mytest.txt";
// Current state of the external media
String extState = Environment.getExternalStorageState();
// External media can be written onto
if (extState.equals(Environment.MEDIA_MOUNTED))
{
try {
// Make sure the path exists
boolean exists = (new File(path)).exists();
if (!exists){ new File(path).mkdirs(); }
// Open output stream
FileOutputStream fOut = new FileOutputStream(path + fname);
fOut.write("Test".getBytes());
// Close output stream
fOut.flush();
fOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
another edit: i will get this working!!
so if i use this line it creates a folder on the sdcard called 'Musictest'. dont understand??
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "test").getAbsolutePath();
////////////////////////////////////////////////////////////////////
Final Edit:
right so this will look for a folder called test in the devices music directory.
if it doesnt exist, it will be created.
(some fixing to be done here, error if empty) it then lists the files in the directory and adds them to an array.
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/test").getAbsolutePath();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
//do your file work here
// Make sure the path exists
boolean exists = (new File(path)).exists();
//if not create it
if (!exists){ new File(path).mkdirs(); }
File sd = new File(path);
//This will return an array with all the Files (directories and files)
//in the external storage folder
File[] sdDirList = sd.listFiles();
if (sdDirList != null)
{
//add the files to the spinner array
array_spinnerLoad=new String[sdDirList.length];
files = new String[sdDirList.length];
for(int i=0;i<sdDirList.length;i++){
array_spinnerLoad[i] = sdDirList[i].getName();
files[i] = sdDirList[i].getAbsolutePath();
}
}
}
}
as mentioned in the docs, getExternalFilesDir() return File. And File object can represent either file or directory.
Therefore:
File musicDirectory = new File( getExternalFilesDir(Environment.DIRECTORY_MUSIC));
Will give you the object to play with.