Finding a line that contain a string using contains method - java

I have two files:
One is a CSV file that contains the following:
Class
weka.core.Memory
com.google.common.base.Objects
client.network.ForwardingObserver
Second is a txt file that contains the following:
1_tullibee com.ib.client.ExecutionFilter
107_weka weka.core.Memory
101_netweaver com.sap.managementconsole.soap.axis.sapcontrol.HeapInfo
107_weka weka.classifiers.Evaluation
guava com.google.common.base.Objects
57_hft-bomberman client.network.ForwardingObserver
18_jsecurity org.jsecurity.web.DefaultWebSecurityManager
I would like to retrieve the lines in the txt files that contain the classes in the CSV file. To do so:
try (BufferedReader br = new BufferedReader(new FileReader("/home/nasser/Desktop/Link to Software Testing/Experiments/running_scripts/exp_23/run3/CSV/MissingClasses_RW_No_Reduction.csv"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println("==>> " + line);
Scanner scanner = new Scanner(new File("/home/nasser/Desktop/Link to Software Testing/Experiments/running_scripts/exp_23/selection (copy).txt"));
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
if(currentLine.contains("**>> " + line)){
System.out.println(currentLine);
}else {
System.out.println("not found");
}
}
}
}
When I run it, I get not found with all the classes in the CSV which is not the case I expect. I expect the following lines to be printed:
107_weka weka.core.Memory
guava com.google.common.base.Objects
57_hft-bomberman client.network.ForwardingObserver
How to solve that?

If you don't want the not found and the ==>> * output, just delete the corresponding lines of code
try (BufferedReader br = new BufferedReader(new FileReader("csv.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Scanner scanner = new Scanner(new File("copy.txt"));
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
if (currentLine.contains(line)) {
System.out.println(currentLine);
}
}
scanner.close(); // added this, could use try-with but that is *advanced*
}
}
this will generate the following output, exactly as requested:
107_weka weka.core.Memory
guava com.google.common.base.Objects
57_hft-bomberman client.network.ForwardingObserver
obviously used files located in my folder...

Just my two cents: If you're using Java 8, and the CSV file is relatively small, you can simply do this:
List<String> csvLines = Files.lines(Paths.get(csvFilename))).collect(Collectors.toList());
Files.lines(Paths.get(txtFileName)))
.filter(txtLine -> csvLines.stream().anyMatch(txtLine::contains))
.forEach(System.out::println);

Related

Read a text file into list in Java

Python has a method lines = f.read().splitlines() by which we can read a file into list. Do we have a similar method in Java?
You can use Scanner and then read line by line and insert the line into a list
Scanner fileScanner= new Scanner(new File("yourfile.txt");
List<String> lines=new ArrayList();
while(scanner.hasNext()){
String line = scanner.next();
lines.add(line);
}
File in= new File(new URI("file://server/folder/text.txt"));
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Note: The file path has to be a URI that can't contain spaces.
Files conains static metods https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
new String(Files.readAllBytes(Paths.get(path)))
.split(System.lineSeparator);

How to append 4 digit number to the next string read from file

I have one file to read which is like this
mytxt.txt
1234 http://www.abc.com
8754 http://www.xyz.com
I tried with this
try {
// make a 'file' object
File file = new File("e:/mytxt.txt");
// Get data from this file using a file reader.
FileReader fr = new FileReader(file);
// To store the contents read via File Reader
BufferedReader br = new BufferedReader(fr);
// Read br and store a line in 'data', print data
String data;
while((data = br.readLine()) != null)
{
//data = br.readLine( );
System.out.println(data);
}
} catch(IOException e) {
System.out.println("bad !");
}
I used this but the actual question is I want to read one this two charachter one by one and then appens the digit to the link which I'll read as string.
Can anyone tell me how I am suppose to do that..?
any help would be appreciated.
Parse the line you are reading, search for the first white space (I'm assuming you have only one space separating your digit and your url) something like this:
try {
// make a 'file' object
File file = new File("e:/mytxt.txt");
// Get data from this file using a file reader.
FileReader fr = new FileReader(file);
// To store the contents read via File Reader
BufferedReader br = new BufferedReader(fr);
// Read br and store a line in 'data', print data
String data;
while((data = br.readLine()) != null)
{
int posWhite = data.indexOf(' ');
String digit = data.substring(0, posWhite);
String url = data.substring(posWhite + 1);
System.out.println(url + "/" + digit);
}
} catch(IOException e) {
System.out.println("bad !");
}
Is this what you want?
while((data = br.readLine()) != null)
{
String[] data=br.readLine().split();
if(data!=null&&data.length==2)
{
System.out.println(data[1]+"/"+data[0]);
}else
{
System.out.println("bad string!");
}
}
In the while((data = br.readLine()) != null), make the code like this:
String tmpData[] = data.split(" ");
System.out.println(tmpData[1] + "/" + tmpData[0]);

check if a value exists in an external file (java)

Is it possible (and wise) to check if a value exists in an external text file.
So if i have a file: bankcodes.txt that contains the next lines:
INGB
ABNA
...
Is it possible to check if a value is present in this file?
The reason is that these values can change and need to be easily changed whitout making a new jar file.
If there is another, wiser way of doing this i would like to hear it too.
From here:
https://stackoverflow.com/a/4716623/110933
Read contents of file line by line and check the value you get for "line" for the value you want:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Give example how i did it , while File.txt -> our text and ourValue it the one we searching
String ourValue="value"
BufferedReader br = new BufferedReader(new FileReader("File.txt"));
String line = br.readLine();
boolean exist = false;
while (line != null&&!exist) {
if (ourValue.equals(line)) {
exist = true;
} else {
line = br.readLine();
}
}
System.out.println("the value " +ourValue+" exist in the Text? "+ exist);
}

Reading from a text file in Java

I have a text file like this:
Item 1
Item 2
Item 3
I need to be able to read each "Item X" into a string and ideally store all the strings as a vector / ArrayList.
I tried:
InputStream is = new FileInputStream("file.txt");
is.read(); //looped for every line of text
but that seems to only handle integers.
Thanks
You have several answers here, the easiest would be to us a Scanner (in java.util).
It has several convenience methods like nextLine() and next() and nextInt(), so you could simply do the following:
Scanner scanner = new Scanner(new File("file.txt"));
List<String> text = new ArrayList<String>();
while (scanner.hasNextLine()) {
text.add(scanner.nextLine());
}
Alternatively you could use a BufferedReader (in java.io):
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
List<String> text = new ArrayList<String>();
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
However Scanners are generally easier to work with.
You should use FileUtils to do this. It has a method named readLines
public static List<String> readLines(File file, Charset encoding) throws IOException
Reads the contents of a file line by line to a List of Strings. The file is always closed.
See #BackSlash's comment above to see how you're using InputStream.read() wrong.
#BackSlash also mentioned you can use java.nio.file.Files#readAllLines but only if you're using Java 1.7 or later.
You could use Java 7's Files#readAllLines. A short one-liner and no 3rd party library imports necessary :)
List<String> lines =
Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
String [] tmp ;
while (line != null) {
sb.append(line);
tmp = line.Split(" ");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Scanner scan = new Scanner(new FileInputStream("file.txt"));
scan.nextLine();

Reading a text file in java

How would I read a .txt file in Java and put every line in an array when every lines contains integers, strings, and doubles? And every line has different amounts of words/numbers.
I'm a complete noob in Java so sorry if this question is a bit stupid.
Thanks
Try the Scanner class which no one knows about but can do almost anything with text.
To get a reader for a file, use
File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
new FileInputStream (file), encoding));
... use reader ...
reader.close ();
You should really specify the encoding or else you will get strange results when you encounter umlauts, Unicode and the like.
Easiest option is to simply use the Apache Commons IO JAR and import the org.apache.commons.io.FileUtils class. There are many possibilities when using this class, but the most obvious would be as follows;
List<String> lines = FileUtils.readLines(new File("untitled.txt"));
It's that easy.
"Don't reinvent the wheel."
The best approach to read a file in Java is to open in, read line by line and process it and close the strea
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console - do what you want to do
System.out.println (strLine);
}
//Close the input stream
fstream.close();
To learn more about how to read file in Java, check out the article.
Your question is not very clear, so I'll only answer for the "read" part :
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("fileName"));
String line = br.readLine();
while (line != null)
{
lines.add(line);
line = br.readLine();
}
Common used:
String line = null;
File file = new File( "readme.txt" );
FileReader fr = null;
try
{
fr = new FileReader( file );
}
catch (FileNotFoundException e)
{
System.out.println( "File doesn't exists" );
e.printStackTrace();
}
BufferedReader br = new BufferedReader( fr );
try
{
while( (line = br.readLine()) != null )
{
System.out.println( line );
}
#user248921 first of all, you can store anything in string array , so you can make string array and store a line in array and use value in code whenever you want. you can use the below code to store heterogeneous(containing string, int, boolean,etc) lines in array.
public class user {
public static void main(String x[]) throws IOException{
BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
String[] user=new String[500];
String line="";
while ((line = b.readLine()) != null) {
user[i]=line;
System.out.println(user[1]);
i++;
}
}
}
This is a nice way to work with Streams and Collectors.
List<String> myList;
try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
myList = reader.lines() // This will return a Stream<String>
.collect(Collectors.toList());
}catch(Exception e){
e.printStackTrace();
}
When working with Streams you have also multiple methods to filter, manipulate or reduce your input.
For Java 11 you could use the next short approach:
Path path = Path.of("file.txt");
try (var reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
Or:
var path = Path.of("file.txt");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
Or:
Files.lines(Path.of("file.txt")).forEach(System.out::println);

Categories

Resources