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++;
}
Related
So I'm trying to make a file reader to read from x line to y line but when i execute the program it reads all the lines of the file and not the lines that should have started and ended, For example if i'm looking an ID in the file it should print de ID, The name of the holder(the next line of the ID Line), and his/her address(Next line of the name Line), but instead of print just that it prints all the ID'S, Names and Addresses of everyone in the file.
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line2;
int count = 0;
try {
BufferedReader input = new BufferedReader(new FileReader(file));
Scanner input2 = new Scanner(file);
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while((line2 = input.readLine()) != null)
{
if(line2.contains(CL.getID()))
{
while(((line2 = readers.readLine()) != null) && readers.getLineNumber() <= count + 3)
{
count++;
System.out.println(line2);
}
input.close();
input2.close();
output.close();
readers.close();
break;
}
}
}catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
I've modified your code because the problem was at the count++ which will eventually led to reading all the lines from your files, and at the line2 = readers.readLine() which will read from the first line of the file again ( the program works half correct because it reads only 3 lines and only if line2 contains your ID ). Now, to make your program work correctly, you need to either use the BufferedReader or the LineNumberReader.
public static void main(String[] args) {
System.out.println("Escriba el ID Del Cliente");
String line2;
File file = new File(yourpathhere);
int lineCount = 0;
try {
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((line2 = readers.readLine()) != null) {
lineCount++;
if (line2.contains(CL.getId())) {
while (line2 != null && readers.getLineNumber() <= lineCount + 3) {
System.out.println(line2);
line2 = readers.readLine();
}
output.close();
readers.close();
break;
}
}
} catch (IOException ex) {
System.out.println("ERRORR!!!!!!");
}
}
PS : pay attention for the getLineNumber() method because it increments the lines read until the moment you're calling it. It means that if we didn't had the lineCount and the ID we're trying to find was at the 6th line, the getLineNumber() value at the moment when line2.contains(CL.getId()) == true was 6, so the readers.getLineNumber() <= 3 will be FALSE and the program won't work correctly anymore. ( We need to keep track for the lines read until the moment we check for the id )
Assuming you have a file with 100 lines and you want to check and print out line 5 to 10 you could try this:
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line;
int count = 0;
int xLine = 5;
int yLine = 10;
try (BufferedReader input = new BufferedReader(new FileReader(file)))
{
while((line = input.readLine()) != null)
{
if(count < xLine)
{
// skip all lines lower then start
continue;
}
else if(count >= xLine && count <= yLine && line.contains(CL.getID()))
{
// print line if line is between lines to read
// and if line contains ID
System.out.println(line);
}
else
{
// break if count is bigger then yLine
break;
}
count++;
}
}
catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
You read all lines till the BufferedReader reaches null. You check if the line contains your ID. Then you check if the count is between the linenumbers you want to check / print. Then you increment the count for the lines processed.
I simplified the try-catch-Block with a try-with-ressources Statement. As for now I don't see what your plans with output and scanner were, so I removed them.
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.
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 am been searching online and on here on how I can remove a line that contains one or two words but I can't find anything on java. This is the code I have right now:
try {
BufferedReader reader = new BufferedReader(new FileReader("Readfile.txt"));
String line = reader.readLine();
while(line !=null)
{
for(int i = 0 ; i<newarray.length;i++){
if(line.contains(newarray[i])){
System.out.println(line);
}
}
line=reader.readLine();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
It reads sentences from a text file, but before it prints them out, I want to delete some sentences that contains a keyword, e.g. fun.
Something like this:
//BufferedReader stuff etc.
List<String> words = new ArrayList<String>();
words.add("fun");
words.add("something");
String line;
while( (line = br.readLine()) != null)
{
boolean found = false;
for(String word: words)
{
if(line.contains(word))
{
found = true;
break;
}
}
if(found) continue;
System.out.println(line);
}
if(line.contains(newarray[i])){
line = line.replace("fun" ,"");
System.out.println(line);
}
Try this it will delete the word before printing it.
Okay, I tried everything but I can't find answer. My data reader skips empty next line while reading from a txt file.
It is supposed to strip all the comments from the txt file and print rest of the data as it is. My reader does strip the comments & prints the data but it skips the empty new lines..
MyDataReader.java
public String readLine()
{
String buf = new String();
String readStr = new String();
int end = 0;
int done = 0;
try
{
// checks if line extraction is done and marker has non null value
while (done != 1 && marker != null)
{
readStr = theReader.readLine(); // Reads the line from standard input
if (readStr != null)
{
/* If the first character of line isnt marker */
if (readStr.length() > 0)
{
if (!readStr.substring(0, 1).equalsIgnoreCase(marker))
{
end = readStr.indexOf(marker); // checks if marker exists in the string or not
if (end > 0)
buf = readStr.substring(0, end);
else
buf = readStr;
done = 1; // String extraction is done
}
}
}
else
{
buf = null;
done = 1;
}
}
}
// catches the exception
catch (Exception e)
{
buf = null;
System.out.println(e);
}
return buf;
}
TestMyDataReader.java
String myStr = new String();
myStr = _mdr.readLine();
while (myStr != null)
{
//System.out.println("Original String : " + myStr);
System.out.println(myStr);
myStr = _mdr.readLine();
}
if (readStr.length() > 0)
That's the line of code that is skipping empty lines.
lots of issues in this code, but the main problem that you are dealing with is that new lines are not included in the readLine result. Thus, your if statement is not true (the line is in fact empty
Your reader won't include the newline characer in readStr, so reading in the line "\n" will make readStr be "", and
readStr.length() > 0
Will evaluate to false, thus skipping that line.