Get content from a text file to String (Android) (FileNotFound) (Java) - java

I want to get the text from a text file I have in my project (android studio) and make that text to a string. I am currently having trouble getting the correct path or something. I'm using two methods I found here on Stackoverflow to get the textfiles to Strings. These are the methods:
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
And I'm calling the methods like this, and I have tried all kinds of pathing but none seems to work:
Log.i("er0r", Solve.getStringFromFile("\\tables\\lowerLayer\\cross\\whiteRed.txt"));
This is just an attempt to print the content of the textfile. I get the following error: java.io.FileNotFoundException: .\tables\lowerLayer\cross\whiteRed.txt: open failed: ENOENT (No such file or directory)
This is how I have ordered my packages:
http://imgur.com/a/rK9R5
How can i fix this? Thanks
EDIT:
public String LoadData(String inFile) {
String str = "";
try{
StringBuilder buf=new StringBuilder();
InputStream json=getAssets().open(inFile);
BufferedReader in=
new BufferedReader(new InputStreamReader(json, "UTF-8"));
while ((str=in.readLine()) != null) {
buf.append(str);
}
in.close();
} catch (Exception e) {
Log.e("er0r", e.toString());
}
return str;
}
Tried this with inFile = "assets\whiteRed.txt"
Got me this error: java.io.FileNotFoundException: assets\whiteRed.txt
ADDITIONAL CODE:
Constructor of the class that's calling the LoadData method
public class Solve {
private Context context;
//constructor
public Solve(Context context){
this.context = context;
}

If at design time, in Android Studio, you want to supply files which your app can read at run time then put them in the assets folder of your Android Studio project.
Maybe you have to create that assets folder first.
After that your app can read those files from assets using assets manager.
Just google for how to do this exactly. All has been posted here many times.

Related

Using information contained in text files

I have a problem with the task and I would like to ask for tips.
There are three text files with the names: doctors.txt, patients.txt, visits.txt.
They contain information about doctors, patients and home visits.
In each of the files, the data in the line are separated by tabs.
Using the information contained in the files, execute the following commands:
find the doctor who has had the most visits.
I am having trouble reading these files. How do I do this to convert the data from these three text files?
I created the doctor, patient, visit, time classes and in the main I put the files into the blackboard.
enter code here
public static void main(String[] args) throws IOException {
File[] files = {new File("doctors.txt"), new File("patients.txt"),
new File("visits.txt")};
for (File file : files) {
if(file.isFile()) {
BufferedReader inputStream = null;
String line;
try {
inputStream = new BufferedReader(new FileReader(file));
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
}catch(IOException e) {
System.out.println(e);
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
}

Best way to read data from 16MB file without freezing the app

I have a problem and can't find a good solution to it. I need to read a textfile with large amount of data (file has 16MB). The file contains 12 columns with integer values in each one. Generally my problem is how to do this without freezing the app. I have my file in the assets folder of my project and I tried using something like this:
AssetManager assetManager = this.getAssets();
try {
InputStream inputStream = assetManager.open("3333.ecg");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str = bufferedReader.readLine()) != null) {
stringBuilder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
But app freezes. My goal is to get the data from each column and save it into an arraylist of integers. I'm looking for some advice.
Thanks in advance.
Use this to run it in background:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
AssetManager assetManager = this.getAssets();
try {
InputStream inputStream = assetManager.open("3333.ecg");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str = bufferedReader.readLine()) != null) {
stringBuilder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});

How to read a yaml file to a string with the correct indentation

I need to read a yaml file and get the content of it to a String.
As the yaml format need the right indentation, I have to get the exact content as in the file. The normal way of reading a file in java doesn't work for me.
So if anyone can tell me how to read the content of a yaml file into a String variable.
Again the question is,
How to read the content of a yaml file with the indentation and spaces and get the content of the file into a String variable in java? In other words, I need the content of the yaml file as it is to a String variable.
Anyway, you have figured it out, but here is the code for proper indentation.
package test;
import java.io.BufferedReader;
import java.io.FileReader;
public class test {
private static String FILENAME = "input.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
StringBuffer stringBuffer = new StringBuffer();
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
stringBuffer.append(sCurrentLine);
stringBuffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(stringBuffer);
}
}

ASCII file in Eclipse plugin project not visible after export

Am am working on an Eclipse plugin project. Inside that project I have a folder resources, which contains a simple ASCII file, which contains lines with Strings. These Strings are used in a drop down menu, by the ui. If I run a new launchtime Eclipse everything works like it should and the file content is successfully used by the drop down menu but if I export the application and run it, the drop down menu is empty, which means, that the file can't be read.
Inside the plugin.xml (Build tab) I've marked the resource folder (which contains the ASCII file) in the binary build.
This is how I extract the file line by line:
public class ParameterExtractor {
private final static String FILE_PATH = "/resources/parameters";
public ArrayList<String> extractParameters() throws IOException {
ArrayList<String> params = new ArrayList<String>();
URL url = FileLocator.resolve(getClass().getResource(FILE_PATH));
URI uri = null;
try {
uri = url.toURI();
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (uri != null) {
try {
File file = new File(uri);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
params.add(line);
}
fileReader.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
return params;
}
}
And this is how I use the returned ArrayList:
ArrayList<String> params = new ArrayList<String>();
try {
params = new ParameterExtractor().extractParameters();
} catch (IOException e1) {
e1.printStackTrace();
}
final Combo combo = new Combo(container, SWT.BORDER);
combo.setItems(params.toArray(new String[params.size()]));
What could cause the problem and how can I solve it?
I would be grateful for any help!
FileLocator.resolve does not guarantee to return you a URL than can be used to read a file. Instead use:
Bundle bundle = ... your plugin bundle
URL url = FileLocator.find(bundle, new Path(FILE_PATH), null);
url = FileLocator.toFileURL(url);
The URL returned by toFileURL is suitable for reading using File and FileReader.

Sonar: visitFile(): How to get the source code file

I'm implementing custom script rule plugin for Sonar.
I want to make a checking rule directly for the source code
and not from checking tokens or nodes of the ASTtree.
Having the follow code:
#Override
public void visitFile() {
BufferedReader br = null;
File file = null;
String line = null;
try {
file = this.getSourceCode().getFile();
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
...
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My problem is that the :
this.getSourceCode().getFile();
returns back null
how can I get the instance of the file for which was actually the visitFile() called?
How does 'visitFile()' works actually?

Categories