Ifstream won't open file C++ with JNA Android Studio - android

I am trying to read in a file using the fstream. I am writing in C++11, but interfacing it with Java via JNI in Android Studio. It doesn't open the file for some reason. I am using a relative file path and I don't understand why it can't open the file. The file is named proverbs.txt. There aren't any discrepancies within the name like proverbs.txt.txt or anything like that.
Here's the code:
void storeProverbs() {
string path = "/Users/tenealaspencer/Desktop/proverbs.txt";
std::ifstream provInput(path.c_str(), std::ios::in);
//provInput.open("/Users/tenealaspencer/Desktop/proverbs.txt");
// opens the proverbs text file
equivInput.open("/Users/tenealaspencer/AndroidStudioProjects/example/app/src/main/cpp/stored.txt"); // opens the stored (English) proverbs text file
if (!provInput.is_open()) {
cout << "error ";
}
while (!provInput.eof()) // while not at the end of the proverbs file
{
getline(provInput, phrase); // read proverbs in line by line
getline(equivInput, storedProv); // read english proverbs in line by line

Never mind I just imported the file via Java using the following code:
try {
InputStream is = getAssets().open("stopwords.txt");
String line1;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while((line1 = reader.readLine()) != null) //
{
try {
byte[] utf8Bytes = line1.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
storeStopWords(line1);
}
}
catch (IOException e) {
e.printStackTrace();
}
try {
InputStream is = getAssets().open("proverbs.txt");
InputStream iz = getAssets().open("stored.txt");
String line;
String line2; //= new String ("");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader reader2 = new BufferedReader(new InputStreamReader(iz));
while((line = reader.readLine()) != null && (line2 = reader2.readLine()) != null ) //
{
try {
byte[] utf8Bytes = line.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
storeProverbs(line,line2);
}
}
catch (IOException e) {
e.printStackTrace();
}
I read somewhere that JNA doesn't support the fstream library or something like that. In any case it works.

Related

Convert input stream into file android

in my application i am using below code that returns input stream
QBContent.downloadFileById(fileId, new QBEntityCallback<InputStream>() {
#Override
public void onSuccess(final InputStream inputStream, Bundle params) {
long length = params.getLong(Consts.CONTENT_LENGTH_TAG);
Log.i(TAG, "content.length: " + length);
// use inputStream to download a file
}
#Override
public void onError(QBResponseException errors) {
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progress) {
}
});
now i want to covert input steam into file then want to do two things with that file
1. how can i save it to user's phone storage
2. save it temporarily and display's it in pdf viewer using intent
note: returned file will be in pdf formal
You did not mentionned if you wanted to store in external or internal storage, I wrote this example for internal storage
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("file.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(total.toString());
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
Don't forget to use try/catch and close what needs to be closed
You can use below code to store InputStream in File.
But you need to pass file path and where you want to store file in storage.
InputStream inputStream = null;
BufferedReader br = null;
try {
// read this file into InputStream
inputStream = new FileInputStream("/Users/mkyong/Downloads/file.js");
br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
System.out.println("\nDone!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to set default open with(dialog) option to my android app?

I have a file in my devise called test.csv. when i click on that file is opened through my app.how to set default open with(dialog) option to my app in android?
above is the sample dailog.how to add my app to the dialog list?
I think you may want to read the csv file. you could get the csv file path. So see the following.
public static void readCSV(File file) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file));// your csv file
reader = new BufferedReader(isr);
String line = null; // every time read one line
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The stringBuilder.toString() is your csv file's content. Sorry for my English.

How to read XML file and pass to setText as String with all tags and white-characters [Android]

I want to read XML file, save it as String and pass to setText. I don't want to parse it but see it on my smartphone screen with all tags and white-characters, eg.
<a>
<b>some text</b>
</a>
not:
some text
How to do it?
FYI, this is how I solve my problem:
public String readXML() {
String line;
StringBuilder total = new StringBuilder();
try {
InputStream is = activity.getAssets().open("subjects.xml");
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
total = new StringBuilder();
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return total.toString();
}
Use FileInputStream to read file:
File file = new File(<FilePath>);
if (!file.exists()) {
System.out.println("File does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
FileInputStream stream = new FileInputStream(file);
char current;
while (stream.available() > 0) {
current = (char) stream.read();
//Do something with character
}
} catch (IOException e) {
e.printStackTrace();
}

CSV file cannot be accessed via BufferedReader in Android

I am trying to read a CSV file using BufferedReader in android. My program works perfectly fine in Java but when I try read those data from Android following error I get.
01-31 17:09:58.466: W/System.err(15912): java.io.FileNotFoundException:
/Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv: open failed: ENOENT (No
such file or directory)
Following code I am using here.
public double getLongitudes() {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] nextLine;
double longitudes = 0;
try {
br = new BufferedReader(
new FileReader(
"/Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv"));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
longitudes = Double.parseDouble(country[5]);
Log.d("worked", "worked");
// System.out.println("Latitude " + longitudes);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return (longitudes);
}}
Any idea why its happening ??
The path /Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv is invalid. This looks like the path to a file on your computer rather than your Android device. You need to push the file to your device or your emulated device and access it from there. Even the Android emulator will not read files directly from your computer's filesystem.
Proper way to store your CSV in Android is:
("/sdcard/Android/data/filename.csv");
The .csv file needs to be in your project resources. You can copy the file into assets folder and read it this way
AssetInputStream asset_stream = (AssetInputStream)getAssets().open("input.csv");
InputStreamReader reader = new InputStreamReader(asset_stream);
BufferedReader br = new BufferedReader(reader);
This is one method that has worked for me before.
Another method would be to put the file into res/raw folder and access it
InputStream file = getResources().openRawResource(R.raw.inputfile);
You can also refer to https://stackoverflow.com/a/3851429/3092829
Hope this helps!
So i have solved my problem.
public class ReadCSV {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] nextLine;
String[] country;
AssetInputStream asset_stream = null;
public String[] getLatitude() {
try {
asset_stream = (AssetInputStream) MainActivity.getContext()
.getAssets().open("Input.csv");
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader reader = new InputStreamReader(asset_stream);
Log.d("logg", "log" + reader);
br = new BufferedReader(reader);
Log.d("logg", "log" + br);
try {
while ((line = br.readLine()) != null) {
country = line.split(cvsSplitBy);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return country;
}
As you can see I am trying to get my latitude by returning it through country. But when I trying get it from another fragment class through this,
String[] lat;
lat = csv.getLatitude();
Log.d("", "" + lat);
Why I don't get latitude back ?

read a text file android

I am trying to make the computer read a text file full of words and add it to an ArrayList. I made it work on a regular Java application, but can't get it to work on Android. Can someone help me out?
try {
FileInputStream textfl = (FileInputStream) getAssets().open("test.txt");
DataInputStream is = new DataInputStream(textfl);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String strLine;
while ((strLine = r.readLine()) != null) {
tots.add(strLine); //tots is the array list
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I keep getting a error. The text file is 587kb, so could that be a problem?
try this.
private static String readTextFile(String fileName)
{
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
String line;
final StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
{
buffer.append(line).append(System.getProperty("line.separator"));
}
return buffer.toString();
}
catch (final IOException e)
{
return "";
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
// ignore //
}
}
}

Categories

Resources