May I ask you to guide me how I can accomplish this problem?
I need to compare an inputWord to a string inside a .txt file and if found, return the whole line but if not, show "word not found".
Example:
inputWord: abacus
Text file content:
abaca - n. large herbaceous Asian plant of the banana family.
aback - adv. archaic towards or situated to the rear.
abacus - n. a frame with rows of wires or grooves along which beads are slid, used for calculating.
...
so on
Returns: abacus with its definition
What i am trying to do is compare my inputWord to the words before the " - " (hyphen as delimiter), if they dont match, move to the next line. If they match, copy the whole line.
I hope it doesnt seem like im asking you to "do my homework" but I tried tutorials around different forums and sites. I also read java docs but i really cannot put them together to accomplish this.
Thank you in advance!
UPDATE:
Here's my current code:
if(enhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
String delimiter = " - ";
String del[];
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (enhancedStem.equals(del[0]))
{
in.close();
databaseOutput.setText(s);
break;
}
}
in.close();
}
catch (FileNotFoundException e) {
databaseOutput.setText("" + e);
}
catch (IOException e1) {
databaseOutput.setText("" + e1);
}
}
Thanks a lot! Here's what I came up, and it returns the definition of inputs properly but the problem is, when i enter a word not found in the textfile, the app crashes. The catch phrase doesn't seem to work. Have any idea how I can trap it? Logcat says NullPointerExcepetion at line 4342 which is
s = in.readLine();
Assuming that the format of each line in the text file is uniform. This could be done in the following manner :
1) Read the file line by line.
2) Split each line based on the delimiter and collect the split String tokens in a temp String array.
3) The first entry in the temp token array will be the word before the "-" sign.
4) Compare the first entry in the temp array with the search string and return the entire line if there is a match.
Following code could be put up in a function to accomplish this :
String delimiter = "-";
String[] temp;
String searchString = "abacus";
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null) {
String s = in.readLine();
temp = s.split(delimiter);
if(searchString.equals(temp[0])) {
in.close();
return s;
}
}
in.close();
return ("Word not found");
Hope this helps.
you may try like:
myreader = new BufferedReader(new FileReader(file));
String text = "MyInput Word";
while(!((text.equals(reader.readLine())).equals("0")));
Related
Driving myself crazy over the simplest thing. I have a JSON file called config.txt. The file is shown below.
{
"UsePipesInGuestData": true
}
All I want to do is get a 2 dimensional array such that:
Array[0] = UsePipesInGuestData and
Array[1] = true
I have been trying for 4 hours with various attempts, my most recent is shown below:
private void getConfig(){
//Function to read the config information from config.txt
FileInputStream is;
BufferedReader reader;
try {
final File configFile = new File(Environment.getExternalStorageDirectory().getPath() + "/guestlink/config.txt");
if (configFile.exists()) {
is = new FileInputStream(configFile);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
if(line!= null) {
line = line.replace("\"", ""); //Strip out Quotes
line = line.replace(" ", ""); //Strip out Spaces
if ((!line.equals("{")) || (!line.equals("}"))) {
} else {
String[] configValue = line.split(":");
switch (configValue[0]) {
case "UsePipesInGuestData":
if (configValue[1].equals("true")) {
sharedPreferences.edit().putString("UsePipes", "true").apply();
} else {
sharedPreferences.edit().putString("UsePipes", "false").apply();
}
break;
}
}
}
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I cannot seem to ignore the lines with the { and } in them.
Clearly there MUST be an easier way. JAVA just seems to take an extremely large amount of code to do the simplest thing. Any help is greatly appreciated.
I believe your condition is incorrect. You try to read the file in the else of the condition (!line.equals("{")) || (!line.equals("}")). Simplifying, your code will run when the following happens:
!(!{ || !}) => { && } (applying De Morgan's law)
This means you will only run your code when the line is "{" AND it is "}" which is a contradiction. Try using simple conditions, like (!line.equals("{")) && (!line.equals("}")) (this is when you want to execute your code).
Additionally, you may be getting end of line characters (\n) in your string, which will make your condition fail ("{\n" != "{"). I suggest you debug and see the actual values you're getting in those lines.
I'm kind of noob in Android and I need help with something. I have a .txt file like this:
#nombre iron will#
#fuerza 6#
#const 6#
#habilidad 6#
#intelig 6#
#vitalidad 42#
#aguante 72#
What I want to do is to get every item in the .txt file and store it in a variable. For example, in this case I want a String variable called "nombre" with the value "Will", an int variable "fuerza" with the value "6", etc.
How can I get this? Thanks in advance, and sorry about my bad english.
My code so far:
File tarjeta = Environment.getExternalStorageDirectory();
File carpeta = new File(tarjeta.getAbsolutePath() + "/Rol/PJs/");
File archivo = new File(carpeta.getAbsolutePath(), archivoabierto); //String archivoabierto = "name.txt"
StringBuilder text = new StringBuilder();
try{
//This is where I get lost, I don't know how to proceed
BufferedReader br = new BufferedReader(new FileReader(archivo));
String line;
while ((line = br.readLine()) != null){
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e){
Toast.makeText(Personajes.this, "No se pudo cargar "+archivo.getPath(), Toast.LENGTH_SHORT).show();
}
EDIT:
I'm using json format now and it works. Thanks all!
you could also use
String[] parts = text.split(" ");
String key = parts[0];
String value = parts[1];
but i recommand to use json-format.
Please use SharedPreferences to store key-values, It is much easier.
http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/
I am trying to learn how basic operations work in android apps. I have a .txt file in row folder and I can't read anything. Because when I execute the code (although I don't get any logcat errors) after one second, the emulator turns into a black screen.
String str="";
InputStream is=getResources().openRawResource(R.raw.readme);
StringBuilder finalstring=new StringBuilder();
BufferedReader bf=new BufferedReader(new InputStreamReader(is));
try {
while(str!=bf.readLine()){
finalstring.append(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView tv=(TextView)findViewById(R.id.tvli);
tv.setText(finalstring);
Your while loop appears to be the problem. The condition in it doesn't really make sense. Try:
while((str = bf.readLine()) != null){
finalstring.append(str);
}
Your current loop will never run, as it will evaluate to "while str doesn't equal the line form my text file"
Replace your while statement with this:
while((str = bf.readLine()) != null) {
finalString.append(str);
}
I am reading a txt file containing unicode characters. I need to find whether a specific unicode character exist in this file. The code so far is as follows,
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("DistinctWords.txt"), "UTF-8"));
int i = 0;
String mLine = reader.readLine();
while ((mLine != null)) {
//process line
//unicode value taken from http://codepoints.net/U+0D85
if (mLine.contains("\u0D85")){
i++;
}
mLine = reader.readLine();
}
reader.close();
Log.i("tula", "Ayanna - " + String.valueOf(i));
} catch (IOException e) {
//log the exception
}
Problem: Value of "i" is always "0". When I open the same text file from notepad I can see the letter but my code fails to find it.
Like TronicZomB says, I think you need to be looking for the actual character, like:
while ((mLine != null)) {
//process line
if (mLine.contains("අ")){
i++;
}
mLine = reader.readLine();
}
You will want to use an editor that can handle the proper encoding:
Notepad on Windows will allow you to specify UTF-8 encoding on your file, but you have to set the encoding on the file to UTF-8 from ANSI.
On mac OS-x you can use TextEdit. In the preferences, with the open & save tab, you can set the document encoding.
On Linux StarOffice supposedly works, but I haven't used it.
because i am only reading a very simple csv, where only strings are comma separated and should be converted to a String[].
I thought this was so easy a external jar would be a bit to much and i could handle this very easy. But what happens is that the first item get added until the memory is full and crash!
public List readWinkels(Activity a){
List winkelList = new ArrayList();
try{
InputStream winkelcsv = a.getResources().getAssets().open("winkels.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(winkelcsv, "UTF-8"));
String s = br.readLine();
while (s != null){
winkelList.add(s);
System.out.println(s.toString());
}
br.close();
for(int i =0;i<winkelList.size();i++) {
System.out.println(winkelList.get(i));
}
}catch(IOException ioe){
ioe.printStackTrace();
}
return winkelList;
here is my code.... i dont get why it doesnt work, can anyone help? A readline reads the line and then the reading points jumps to the next line (i think) so why is the first line added a zillion times?
Here's the standard idiom for using a while loop to iterate over lines of a file, applied to your code:
String s;
while ((s = br.readLine()) != null){
winkelList.add(s);
System.out.println(s.toString());
}
You need to call readLine() at every iteration through the loop. The original code is nothing but an infinite loop, since s is only read once. Assuming s is not null, the loop condition is never false, so the list grows without bound until all available memory is used.