Reading and existing file in Xamarin withC# - android

This code works:
string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "File.text");
File.ReadAllText(file);
Pretty straight-forward, but when I display the variable "file" using a Pizel 5 simulator I get a weird path: /data/user/0/com.companyname.aikidohours/files/.local/share/File.text. I can write new data to the file and read from it. but I now want to read from an existing file and I can't figure out where to put the file. Can someone tell where to put a text file full of basic information that I need to read from in Xamarin for adnroid?
Thanks
Todd

If you want to deploy that file with your application, you can add it to the 'Assets' folder inside your_project_name.Android project.
WARNING!!! File put in this folder are READONLY!
In case this is ok for you,this is the code to access the file:
using Xamarin.Essentials;
using (var reader = new StreamReader(await FileSystem.OpenAppPackageFileAsync("file_path")))
{
string content = reader.ReadToEnd();
}

Related

Kotlin: Cannot get FileReader to find file

For an Android App, I'm trying to use the FilerReader function to read my csv file, but after trying everything I cannot get to find my file. I'm using Android studios on a Mac.
Below is my code inside OnCreate():
val filereader = BufferedReader(FileReader("sgsraagadata.csv"))
I have tried placing the csv file inside assets & all resource folders including a raw-type folder.
Similar posts on Stackoverflow suggests that I find the directory that is being searched so that I can put the csv file in that directory. But when I follow their instructions below is what I get.
When I use:
println(System.getProperty("user.dir"))
It prints "/". And when I use:
println(File(".").getAbsoluteFile())
It prints "/."
Given these printed outputs, where should I put the csv file?
*Also added an image showing csv file in assets folder as per suggestion in comments. Result is still an file not found error.
Put your file in assets folder and open it like this:
val file = context.assets.open("sgsraagadata.csv")
val isr = InputStreamReader(file)
val reader = BufferedReader(isr)
var line = reader.readLine()
while (line != null) {
// do something with the line
line = reader.readLine()
}
supply a valid Context or inside an activity you can omit it.

what is OpenNLP's model file path?

I try to use OpenNLP in an Android application with eclipse, and I imported the 4 JARs into the libs folder.
It's probably a stupid question.. but where should I put the model files "en-pos-maxent.bin"? I can't find anything regarding the path anywhere
I try to run the code contains this line:
POSModel model = new POSModelLoader()
.load(new File("en-pos-maxent.bin"));
I tried putting the en-pos-maxent.bin inside a new folder within the project("tagger/en-pos-maxent.bin"), inside the libs folder, or simply give the path where the en-pos-maxent.bin is put when downloaded("Users/ariel/Downloads/en-pos-maxent.bin"), it always give me the error: POS Tagger model file does not exist path: (the path I typed in)
Could anybody help please?
When you use new File("filename") the file is expected to be in the current working directory, I don't think that's different on Android. You can use System.getProperty("user.dir") to get the current working directory. It's by default the directory you start the program from. You could also specify a full path like new File("/full/path/filename") instead.
In android the right way to add file to the application (inside APK) is to put into the assets folder. Then you can't get File object from assets folder but, you can create that File using a buffer or in you case just get it into the InputStream. For example if you will create models folder into the assets folder (assets/models), your code will look like this:
AssetManager am = getAssets();
InputStream inputStream = am.open("models/en-pos-maxent.bin");
POSModel posModel = new POSModel(inputStream);

FileNotFoundException in an Android app: can't find the route to copy the file

Good afternoon everyone,
I'm having a problem here with an CSV file that I wanna use to fill a dynamic table in Android.
I placed the file in the "data" folder of my emulator, and I did the following declaration to create my file variable:
file = new File("/data/Motors.csv");
I used a CSVReader class posted on another thread from this page (Link to the class) and also declared the following line to do the parse:
readerCSV = new CSVReader(new FileReader(file),';','"',0);
In the last line, the programmer to be able to create the variable has to send as parameters a Reader (Or a FileReader, it doesn't make a difference), the separator char, the quote char and the number of how many lines the CSV reader has to skip.
The problem comes that no matter in which directory (Not even in the root directory, which Java tells me that it's "/" through the file.getAbsolutePath(); method) it always gets to the point when the program throws the FileNotFoundException and I'm getting a bit frustrated because I have 2 days already with this problem.
If someone could please help me to get a bit of orientation of what I should do to get the file from the right directory... It would be a lot of help and I can go further with the code I have to finish.
Many thanks in advance!!!!
EDIT
I found a solution to open my file:
I have used 2 file variables: one gets the rout of the External Storage Directory (see first answer in the following link) and the other is declared as a new file, like the following lines in the code:
route = Environment.getExternalStorageDirectory();
file = new File(route,"Motors.csv");
Later I used again the CSV reader class that I found, where the first parameter is from the FileReader type (Sorry #Rajesh, but I couldn't use your alternative because you passed a FileDescription parameter from the AssetManager to the CSV reader class and then I had to change the whole class and that didn't help my problem at all).
Now I don't get the exception at all!!
There are various Storage Options in Android. Files can be stored in internal and external storages. If the CSV file is a static resource, you could think of bundling the file in the "assets" folder of your project.
If you are using the "assets" route, the following code segment can get you a CSVReader.
AssetManager am = getAssets();
AssetFileDescriptor afd = am.openFd ("Motors.csv");
FileDescriptor fd = afd.getFileDescriptor();
readerCSV = new CSVReader(fd, ';','"',0);
The above code snippet doesn't perform error/exception handling, please remember to take care of that. You need to copy the Motors.csv file to the "assets" folder within the project.

Accessing an app's project files on the Android platform

So in my Eclipse android project I have a pdf file that I'd like to open, I looked up the standard address on the android developer's page and I came up with this pointer:
File file = new File("Android/data/com.alex.testing.app/res/raw/jazz.pdf");
where jazz.pdf is situated in res->raw in my eclipse project,
and com.alex.testing is my package name.
Still, when I try if(file.exists()) , the function returns false (on the emulator it goes to an else I've set up to display an error message)...
Sorry for the newbie question, but I'm really stuck with this :(.
put the file in assets folder and pick the file from there
Now use Context.getAssets().open("jazz.pdf") and pass the resulting InputStream into PDf parser library
Ok, to access resources from current application you can use something like,
Uri path = Uri.parse("android.resource://<you package>/raw/<your_file.pdf>");
OR
Uri path = Uri.parse("android.resource://" + getPackageName() + "/" R.raw.<your_file.pdf>);
But I have a doubt if you are trying to use this pdf file in your application then its OK, but If you want to view this file using any third party application then I think you can't do it.
Because external application can't access application's package resources file.
So better way it to put this file in /asset directory then copy it to any public access area then view that file from that path.
//if your are stored in SDcard your location would be
"data/data/com.alex.testing/res/raw/jazz.pdf"
//you read resources from raw folder thru the below code
InputStream inputStream = getResources().openRawResource(R.raw.jazz);
byte[] reader = new byte[inputStream.available()];

File not found issue in Android

I need to access myfile.txt file using FileReader in Android , please suggest me where to add the text file in Eclipse. I tried it adding it in Resource and Asset but I am getting File not found issue.
FileReader fr = new FileReader("myfile.txt");
Even
File ff = new File("myfile.txt");
File Supports only the below listed parameters
FileReader Supports only the below listed parameters
Note: I want solution for this issue , only with FileReader or File
The directory would be /res/raw/ this is where you put all your extra resources.
you can refer to it using getResources().openRawResource(resourceName)
and check here Android how to get access to raw resources that i put in res folder?
EDIT:
how can i edit the text files in assets folder in android
in short
the easiest way would be to copy the file to external directory then do your stuff there
link is here
Android: How to create a directory on the SD Card and copy files from /res/raw to it?
One thing to mention - prior to 2.3 the file size in the assets cannot exceed 1MB.
hope it helps abit
That's how I obtain my file from the SD card, perhaps this can be some use to you.
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File options = new File(getAppDirectory(), "portal.xml");
}
The getAppDirectory method used in the bit of code looks like this :
private String getAppDirectory() {
return new String(Environment.getExternalStorageDirectory().toString()
+ "/foldername/foldername/");
}
After this bit of code I also make sure the file exists and what not before I attempt to read from it.

Categories

Resources