Removing sentences containing a keyword in java - java

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.

Related

How would I print out the first word of each line?

I have a text file that reads like this:
1. Bananas that are not green
2. Pudding that is not vanilla
3. Soda that is not Pepsi
4. Bread that is not stale
I just want it to print out the first word of each line
NOT INCLUDING NUMBERS!
It should print out as:
Bananas
Pudding
Soda
Bread
Here is my code:
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new
FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
Use the split function of String. It returns the array of the String as per the character which we want to split with the string. In your case, it is like as follow.
String sCurrentLine = new String();
reader = new BufferedReader(new
FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
while ((sCurrentLine = reader.readLine() != null) {
String words[] = sCurrentLine.split(" ");
System.out.println(words[0]+" "+words[1]);
}
Java 8+ you can use the BufferedReader's lines() method to do this very easily:
String filename = "Your filename";
reader = new BufferedReader(new FileReader(fileName));
reader.lines()
.map(line -> line.split("\\s+")[1])
.forEach(System.out::println);
Output:
Bananas
Pudding
Soda
Bread
This will create a Stream of all the lines in the BufferedReader, split each line on whitespace, and then take the second token and print it
Please try the code below -:
outerWhileLoop:
while ((sCurrentLine = reader.readLine()) != null) {
//System.out.println(sCurrentLine);
StringTokenizer st = new StringTokenizer(sCurrentLine," .");
int cnt = 0;
while (st.hasMoreTokens()){
String temp = st.nextToken();
cnt++;
if (cnt == 2){
System.out.println(temp);
continue outerWhileLoop;
}
}
}

Empty line in arraylist Java

protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
List<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
System.out.println(line);
}
int k = 0;
for (int i = 0; i < words.size(); i++) {
k++;
String[] splitted = words.get(i).split(":");
String ip = splitted[0];
String port = splitted[splitted.length - 1];
// System.out.println(k + " " + ip + " * " + port);
}
} catch (IOException iOException) {
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to get output printed without empty lines .
These are kind of results am getting Like :
result 1.
result 2.
result 3.
i want output like :
result 1.
result 2.
result 3.
without blank lines.
Don't add the String to the list if it's empty :
if(!line.trim().isEmpty()) {
words.add(line);
System.out.println(line);
}
If you still want to add the blank lines to the list but don't display them, just move the condition :
words.add(line);
if(!line.trim().isEmpty())
System.out.println(line);
Doc
Use System.out.print. Note that the file contains a newline char at the end of each line.
If srcFile is created with Notepad, try removing first the carriage return char System.out.print(line.replaceAll("\\r",""))
ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // remove leading and trailing whitespace
if (!line.isEmpty() && !line.equals("")) {
words.add(line);
System.out.println(line);
}
}

why Java buffered reader missed a lot of lines in output large txt file as input?

Hi I using following code
public class Readfiles {
FileInputStream fr;
public void readAll(){
try {
fr = new FileInputStream(new File("books/Artificial intelligence.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
InputStreamReader reader = new InputStreamReader(fr, decoder);
BufferedReader br = new BufferedReader(reader);
try {
int i = 0;
for(String newLine; (newLine = br.readLine()) != null; )
{
newLine = br.readLine();
i++;
System.out.println(newLine);
}
br.close();
System.out.println(i);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
To read this txt file it is about 420.000 lines long:
Artificial intelligence.txt
But my code above dont read it correctly it is missing about half of the lines in the middle, and seems to start anywhere (each start randomly) the following is one of the possible result of the SYSOut :
Only first lines:
##Margaret H. Szymanski,Paul M. Aoki,Rebecca E. Grinter,Amy Hurst,James D. Thornton,Allison Woodruff
#cComputer Supported Cooperative Work
#%5488
#%87739
#%257074
#%818174
#!
#*Unpacking Tasks: The Fusion of New Technology with Instructional Work.
#t2008
#index831790
#%174882
#!
So the question is Why?
Printout of i is always 209647.
Well you are reading the line twice
once in
for(String newLine; (newLine = br.readLine()) != null; )
{
and then again in
newLine = br.readLine();
nicer would be
while ((newLine = br.readLine()) != null) {....}
You're calling br.readLine() twice in your loop, but only using the result of one of those two calls in your System.out.println call. So you're only printing out every second line.
You're calling br.readLine() twice
for(String newLine; (newLine = br.readLine()) != null; )
{
newLine = br.readLine();
i++;
System.out.println(newLine);
}
You can get rid of the one inside the loop
for(String newLine; (newLine = br.readLine()) != null; )
{
i++;
System.out.println(newLine);
}
for(String newLine; (newLine = br.readLine()) != null; )
{
i++;
System.out.println(newLine);
}

Read File in Java, output the first comma delimited String

I want to extract the first String in a file using the delimiter ",".
Why does this code generate a number of lines greater than one?
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) { e.printStackTrace(); }
}
}
You are printing inside a loop. That's why it is printing multiple times (if that's what you're asking).
String[] splited = read.split(",");
System.out.println(splited[0]);
will just do
EDIT: As Abishek also mentioned, don't read = in.readLine(); again inside your while loop since by doing so you are skipping a line.
while ((read = in.readLine()) != null) {
String[] splited = read.split(",");
System.out.println(splited[0]);
}
What do you mean by number of lines superior to the original ones
If you are using splited[0], why are you keeping inside a loop. It will always get you same string
Not sure why your code works that way but you might try Scanner with a delimeter. Try:
Scanner sc = new Scanner( new File("myNumbers")).useDelimiter(",");
String firstString = sc.next();
/// check for null..
You read in every line from "irisAfter.txt", then split each line on "," into multiple elements, then print out the first element of that line on its own line as many times as there are elements in the line. Multiple lines*multiple elements per line = more lines in output than in input.
Change
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
to
if (splited.length > 0)
{
System.out.println(splited[0]);
}
That way you print out the first element of every line on its own line only one time and only if there actually is a first element.
You are also skipping every other line. If you don't want to do that, remove the line
read = in.readLine();
just below
while ((read = in.readLine()) != null) {.
(You are now reading in a line and then reading in the next line, discarding the first read in line. Then you process that second line, after which the loop starts again, you read in the third line, then read in the fourth line, discarding the third, etc. etc.)
if you modify your code like this, you should get the result you expect.
public static void main(String[] args) {
BufferedReader in = null;
try {
String[] splited;
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
splited = read.split(",");
}
System.out.println(splited[0]);
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
}

Read file and insert data into String[]

public static String[] words = null;
public static String readFile(String name) {
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(name));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
words = everything.split("\\n");//not sure if this is right...
} finally {
br.close();
}
} catch (Exception e) {
e.getMessage();
}
return "Loaded " + i + " words";
}
I'm basically trying to read a file with data on each line. On each line in the file I'm trying to insert into the array. May someone help me figure out what I'm doing wrong here?
The problem is that:
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
sb is never actually appended anything, it is just appending empty strings over and over again.
should be:
while (line != null) {
i++;
sb.append(line);
sb.append("\n");
line = br.readLine();
}

Categories

Resources