I have a users1.txt with some registries like: basketball president tom#gmail.com 1234 and I am making the user to give as input the email,password and two choices of spinner , and I want to search them in the file and compare them , then if its true i will print a message (open() function). In the bellow code the condition was made with success but only for the first line of the file, I want to check all the file for each input of user. To be more specific , I want the search not to stop to basketball president tom#gmail.com 1234 but continues to the second line football referee tam#gmail.com 123123 etc. until the end of file. any suggestion would be great.
signBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if( TextUtils.isEmpty(email.getText()))
email.setError("Email Required");
else if( TextUtils.isEmpty(password.getText()))
password.setError("Password Required");
else {
String text = readFromFile("users1.txt");
String[] splited = text.split("\\s+");
if(SportSpinner.getSelectedItem().toString().equals(splited[0]) && (UserSpinner.getSelectedItem().toString().equals(splited[1])) && (password.getText().toString().equals(splited[3])) && (email.getText().toString().equals(splited[2])))
open(SportSpinner.getSelectedItem().toString(), UserSpinner.getSelectedItem().toString());
else
{
if(tries==1)
open();
signBtn.startAnimation(shakeAnimation);
tries--;
message(tries);
}
}
}
});
}
private String readFromFile(String name){
StringBuilder text = new StringBuilder();
try {
File file = new File(getFilesDir().getAbsolutePath(),name);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}catch(IOException e){
Log.e("Exception", "File read failed: " + e.toString());
}
return String.valueOf(text);
}
If the lines for the file are always in sets of the same number, you can use a loop to increment the indices that you check. I would also add a flag of some sort to stop searching if you found it.
boolean found = false;
for (int i = 0; i <= splitted.length-3 && !found; i += 4) {
if(SportSpinner.getSelectedItem().toString().equals(splited[i]) && (UserSpinner.getSelectedItem().toString().equals(splited[i+1])) && (password.getText().toString().equals(splited[i+3])) && (email.getText().toString().equals(splited[i+2]))) {
found = true;
// Your open method goes here
}
}
if (!found) {
// Now put all the code from the previous else statement here, since it has now searched the whole list for the one set of inputs
}
This checks every line of the file for a match and drops out of the loop if there is a match.
Related
I have a text file with 4 lines of random words, line for line, and I need to be able to read each line and display it to its text field (First line goes into first text field, etc), but it is only reading the last line and displaying it into any text field.
"myfile.txt"
one
two
three
onetwothree
TextField label1Text = new TextField();
TextField label2Text = new TextField();
TextField label3Text = new TextField();
load.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent l) {
String line = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"));
while ((line = reader.readLine()) != null) {
label1Text.setText(line);
label2Text.setText(line);
label3Text.setText(line);
labelO2Text.setText(line);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
primaryStage.show();
}
}
Your current code reads each line in turn, and for each line sets the text of all the labels to that line of text.
Instead, you need to take each label in turn, and set its text to the next line from the file. You can do that with something like:
try (BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"))) {
List.of(label1Text, label2Text, label3Text, label02Text)
.forEach(label -> {
try {
label.setText(reader.readLine());
} catch (IOException exc) {
// handle exception
}
});
}
You are reading a single line, then setting the content of that line to all 3/4 TextFields (there is one missing in your example). After the loop finishes, all TextFields are set to the content of the last line of your file.
There is a variety of ways to achieve what you want - if you only ever have 4 entries, the following will work:
String[] lines = new String[4];
int index = 0;
while ((line = reader.readLine()) != null) {
lines[index++] = line;
if (index==4) break;
}
label1Text.setText(lines[0]);
label2Text.setText(lines[1]);
label3Text.setText(lines[2]);
label4Text.setText(lines[3]);
If you had references to your TextFields in an array, you could also do
int index = 0;
while ((line = reader.readLine()) != null) {
labels[index++].setText(line);
if (index==4) break;
}
The problem sits in your loop
while ((line = reader.readLine()) != null) {
label1Text.setText(line);
label2Text.setText(line);
label3Text.setText(line);
labelO2Text.setText(line);
}
Basically if we look at the loop, first iteration changes all of the labels to the word "One", second iteration in the loop sets all the labels to "Two", than "Three" and last iteration sets all labels as "Four".
To solve the problem you can add a simple counter with some if statements, so it will tell your loop what to do.
int counter = 0;
while ((line = reader.readLine()) != null) {
if(counter == 0)
label1Text.setText(line);
if(counter == 1)
label2Text.setText(line);
if(counter == 2)
label3Text.setText(line);
if(counter == 3)
labelO2Text.setText(line);
counter++;
}
I am sure it is not the most optimal way, but if you want to do it with loop, that's it.
I have loaded from text files many times before without thi issue, I have read and re-read my code and I (personally) cant see why I would get this issue, I am completely lost.
static public ArrayList<Media> importMedia(String fileName) throws IOException
{
try {
ArrayList<Media> mList = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
int numberOfItems = Integer.valueOf(line);
while((line = reader.readLine()) != null)
{
String[] split = line.split(",");
if(split[0].contains("mp3"))
{
Mp3 mp3 = new Mp3(split[1]/*title*/,split[0]/*filename*/,Integer.parseInt(split[4])/*releaseyear*/,split[2]/*artist*/,split[3]/*album*/,split[5]/*label*/,Double.parseDouble(split[6])/*runtime*/);
mList.add(mp3);
}else if (split[0].contains("gif"))
{
Gif gif = new Gif(split[1]/*title*/,split[0]/*filename*/,Integer.parseInt(split[6])/*releaseyear*/,Double.parseDouble(split[2])/*width*/,Double.parseDouble(split[3])/*height*/,split[4]/*equipName*/,split[5]/*equipModel*/);
mList.add(gif);
}else if(split[0].contains("avi"))
{
String castNames = "";
boolean first = true;
for(int i = 7; i < 15; i++)
{
if(!(split[i].isEmpty()))
{
if(first)
{
castNames += split[i];
first = false;
}else{
castNames += "," + split[i];
}
}
}
Avi avi = new Avi(split[1]/*title*/,split[0]/*filename*/,Integer.parseInt(split[3])/*releaseyear*/,split[2]/*studio*/,split[5]/*director*/,castNames/*castnames*/,Double.parseDouble(split[4])/*runtime*/,Integer.parseInt(split[6])/*cast*/);
mList.add(avi);
}else{
}
}
return mList;
} catch (Exception ex) { System.out.println(ex.toString()); }
return null;
}
Now it will only get the first 3 files(Console shown in picture)
I am simply trying to loop through and I am not sure why it would be out of bounds, I cannot see anything wrong with the loop, or why its giving me some but not all.
In this code you are using a String Array split from index 0 to index 14.
It would be good to do some defensive programming by checking length of String Array.
Please check the length of array before proceeding to use it in your programme.
like split.length >14
By using this habit you can always escape from 'ArrayIndexOutOfBoundsException'
I have a .txt file with some text in it.
For example Hello, world.
I'd like to search the whole file and find out how many appearances a string has as well as the position of them, For example "wo" on the above text has one. That number should be placed in an edittext. However I only know how to search a specific char and not whole text, can you please help me? Thanks a lot
BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
int ch;
char charToSearch='a';
int counter=0;
while((ch=reader.read()) != -1) {
if(charToSearch == (char)ch) {
counter++;
}
};
reader.close();
System.out.println(counter);
public static int countWord(String word, FileInputStream fis) {
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String readLine = "";
int count = 0;
try {
while ((readLine = in.readLine()) != null) {
String[] words = readLine.split(" ");
for (String s : words) {
if (s.contains(word))
count++;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
You can use something like:
int nFound = 0;
String target = ".............Your long text..................";
String search = "find this"
int startIndex = 0
do
{
int index = target.indexOf(search, startIndex);
if(index !=-1)
{
// Found
nFound++;
// Here you have the index variable, which says you the position of the found match
/* DO your job */
/* Update the index to start the search again on the rest of the string, until no matches are found*/
startIndex = index+1;
}
else
break;
}while(true);
Before doing this, concatenate the whole text in "target" string, or dexecute the previous code for each line if you are sure the target string is not going to appear at the end of some line and the begining of the next line
If you are using Java 7, then according to this, you can get a String with the whole file in it:
String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);
Then, you can do this:
public void print(String word)
{
String tempStr = null;
int count = 0;
while (tempStr.indexOf(word) != -1)
{
System.out.printf("Position: %d, Count: %d\r\n", tempStr.indexOf(word), ++count);
tempStr = tempStr.substring(tempStr.indexOf(word) + word.length());
}
}
For simplicity, I would read a line and use "string.split(String regex)".
while(readLine) {
String[] str = readLine.split(regex);
//you can tell based on the array, how many matches and their position.
}
You can also use util.Scanner or regex.Pattern.
But if you are looking for performance, I think 'string.indexOf' is the best approach.
So I am trying to extract a piece of code from a txtfile ,the start of the piece being indicated by "# EMPIRES" and the end being indicated by another string starting with a '#'. My program however never finds the start of the piece and keeps on going until it reaches the end of the file.
To try and find out what the problem was I tried first to print every line that it finds.
And here I encountered another problem. My code already stops finding new lines,long before
"# EMPIRES" is even reached.
public String getEmpirestxt(String fileName) {
Scanner sc;
try {
sc = new Scanner(new File(fileName));
String currentLine = sc.nextLine();
StringBuilder empiresText = new StringBuilder(currentLine);
while (!currentLine.startsWith("# EMPIRES")) {
currentLine = sc.nextLine();
System.out.println(currentLine);
}
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
return empiresText.toString();
} catch (FileNotFoundException ex) {
System.out.println("Landed_Titles.txt not found.");
}
return null;
}
The textfile itself :
https://www.wetransfer.com/downloads/a1093792d5ac54b6ccce04afecb9357f20140402095042/505fca
Here is my solution to your problem. I used newBufferedReader instead of the Scanner to read the file. This example works with Java 7.
public String getEmpirestxt2(String fileName) {
Charset charset = Charset.forName("ISO-8859-1");
Path filePath = Paths.get(fileName);
try (BufferedReader reader = Files.newBufferedReader(filePath, charset)) {
String line = null;
// find the start of the piece
while ((line = reader.readLine()) != null && !line.equals(START)) {
}
System.out.println("START: " + line);
// getting the piece
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null && !line.startsWith(END)) {
sb.append(line);
}
System.out.println("END: " + line);
return sb.toString();
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
return null;
}
The constants in the method are:
private static final String START = "# EMPIRES";
private static final String END = "#";
I tested it with your file and it works fine. It also prints the starting and end points of the required piece:
START: # EMPIRES
END: # color={ 144 80 60 }
String currentLine = sc.nextLine();
you are starting reading from the next Line.
The condition:
while (sc.hasNextLine() && currentLine.charAt(0)!='#')
may terminate even if the file has more lines to read, because of the second predicate. If currentLine.charAt(0)!='#' is fales, the while loop ends. This does not mean there are no more lines to read.
In your second while loop you never set currentLine
This part:
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
should be:
do{
currentLine=sc.nextLine();
empiresText.append("\n").append(sc.nextLine());
}while(sc.hasNextLine() && currentLine.charAt(0)!='#');
Otherwise the line right after # EMPIRES won't be read and the code while loop will never stop because the currentLine is not getting updated.
Append currentLine instead of sc.nextLine() in the second while loop :
while (sc.hasNextLine() && currentLine.charAt(0) != '#') {
empiresText.append("\n").append(currentLine);
currentLine = sc.nextLine();
}
Otherwise you can use a single loop like below :
while (sc.hasNextLine()){
if(sc.nextLine().startsWith("# EMPIRES")){
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0) != '#') {
empiresText.append("\n").append(currentLine);
currentLine = sc.nextLine();
}
}
}
I have a dynamic big File and I want check a Boolean value and then if it's true, get count of a thing
please help me
for example this is my file (it maybe has 20000 lines)
.
.
.
fsfds fdsfsdf gfhgfh value1=true fdsfd fdfdsr ewref
dfdfsd dsfds dfdf fdsfsd
dfdfsd dsfds myval dfdf fdsfsd
dfdfsd dsfds dfdf fdsfsd
dfdfsd dsfds myval dfdf fdsfsd
fdfdfddsfds
fdfdsfdfdsfdfdsfsdfdsfdsfdsfds
.
.
.
I wrote this code to handle it but I can't because in this case I read Line by Line and I must check if value1 is true then in 2 line after I must count myval ...
public void countMethod() {
int i = 0; //count
try {
BufferedReader input =
new BufferedReader(new FileReader(new File("I:\\1.txt")));
String line;
while ((line = input.readLine()) != null) {
if (line.substring(line.indexOf("value1")).split("=")[1].equals("true")) {
if (line.indexOf("myval") != -1)
i++;
}
}
input.close();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("Count is : " + i);
}
How can I check condition and after that if it's true I count myvals?
Thanks a lot
If you only want to make one pass through the file, just inspect each line and check both its count of myval and whether it has value1 = true. You'll know what the count of myval is, but you won't have to report it unless value1 is true.
Try:
boolean found = false;
while ((line = input.readLine()) != null) {
if (!found)
found=line.substring(line.indexOf("value1")).split("=")[1].equals("true");
if (found && line.indexOf("myval") != -1)
i++;
}