read and find string from text file - java

I am loading text file contents to GUI using this code:
try {
BufferedReader br = new BufferedReader(new FileReader ("text.txt"));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("TITLE")) {
jTextField2.setText(line.substring(11, 59));
}
}
in.close();
} catch (Exception e) {
}
Then contents of text.txt file:
JOURNAL journal name A12340001
TITLE Sound, mobility and landscapes of exhibition: radio-guided A12340002
tours at the Science Museum A12340003
AUTHOR authors name A12340004
On jTextField2 I am getting this line: "Sound, mobility and landscapes of exhibition: radio-guided".
The problem is I don't know how to get to jTextField2 the string of next line "tours at the Science Museum".
I would like to ask how can I get both line on jTextField2 i.e. "Sound, mobility and landscapes of exhibition: radio-guided tours at the Science Museum"?
Thank you in advance for any help.

If you are using Java 8 and assuming that the columns have a fixed number of characters, you could something like this:
public static void main(String args[]) throws IOException {
Map<String, String> sections = new HashMap<>();
List<String> content = (List<String>)Files.lines(Paths.get("files/input.txt")).collect(Collectors.toList());
String lastKey = "";
for(String s : content){
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length()-9).trim();
if(k.equals(""))
k=lastKey;
sections.merge(k, v, String::concat);
lastKey=k;
}
System.out.println(sections.get("TITLE"));
}
The first column is the key. When the keys does not exist, the last key is used. A Map is used to store the keys and the values. When the key already exist, the value is merged with the existing one by concatenation.
This code outputs the expected String: Sound, mobility and landscapes of exhibition: radio-guidedtours at the Science Museum.
EDIT: For Java 7
public static void main(String args[]) {
Map<String, String> sections = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("files/input.txt"))) {
while ((s = br.readLine()) != null) {
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 9).trim();
if (k.equals(""))
k = lastKey;
if(sections.containsKey(k))
v = sections.get(k) + v;
sections.put(k,v);
lastKey = k;
}
} catch (IOException e) {
System.err.println("The file could not be found or read");
}
System.out.println(sections.get("TITLE"));
}

Why not create a MyFile class that does the parsing for you, storing key-value-pairs in a Map<String, String>, which you can then access. This will make your code more readable and will be easier to maintain.
Something like the following:
public class MyFile {
private Map<String, String> map;
private String fileName;
public MyFile(String fileName) {
this.map = new HashMap<>();
this.fileName = fileName;
}
public void parse() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String key = "";
while (line != null) {
//Only update key if the line starts with non-whitespace
key = line.startsWith(" ") ? title : line.substring(0, line.indexOf(" ")).trim();
//If the key is contained in the map, append to the value, otherwise insert a new value
map.put(key, map.get(key) == null ? line.substring(line.indexOf(" "), 59).trim() : map.get(key) + line.substring(line.indexOf(" "), 59).trim());
line = br.readLine();
}
}
public String getEntry(String key) {
return map.get(key);
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Entry entry:map.entrySet()) {
sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
}
This will parse the entire file first. The expected format of the file is:
0 ... 59
[KEY][WHITE SPACE][VALUE]
0 ... 59
[WHITE SPACE][VALUE TO APPEND TO PREVIOUS KEY]
This allows for variable length keys.
Allowing you to handle exceptions separately, and then easily reference the contents of the file like so:
MyFile journalFile = new MyFile("text.txt");
try {
journalFile.parse();
} catch (IOException e) {
System.err.println("Malformed file");
e.printStackTrace();
}
jTextField2.setText(journalFile.getEntry("TITLE"));

An empty (all spaces) first column indicates that a line is the continuation of the previous one. So you can buffer the lines and repeatedly concatenate them, until you get a non-empty first column, and then write/print the whole line.
try {
BufferedReader br = new BufferedReader(new FileReader("text.txt")) ;
String line ;
String fullTitle = "" ;
while ((line = br.readLine()) != null) {
//extract the fields from the line
String heading = line.substring(0, 9) ;
String titleLine = line.substring(10, 69) ;
//does not select on "TITLE", prints all alines
if(heading.equals(" ")) {
fullTitle = fullTitle + titleLine ;
} else {
System.out.println(fullTitle) ;
fullTitle = titleLine ;
}
}
System.out.println(fullTitle) ; //flush the last buffered line
} catch (Exception e) {
System.out.println(e) ;
}

you can do this
First of all read the entire file into a string object.
then get the indexes of the TITLE and AUTHOR
like int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR");
then add the length of TITLE into start index start+="TITLE".length();
and subtract the length of AUTHOR from end index end-="AUTHOR".length();
at last you have the start and end index of text that you want.
so get the text like.
String title=str.subString(start,end);

Related

Returning Strings from a file between 2 specified strings in java

I've been searching the web and I can't seem to find a working solution.
I have a file containing theses lines:
Room 1
Coffee
Iron
Microwave
Room_end
Room 2
Coffee
Iron
Room_end
I want to print all Strings between Room 1 and Room_end. I want my code to start when it find Room 1, print line after Room 1 and stop when it get to the first Room_end it find.
private static String LoadRoom(String fileName) {
List<String> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
result = reader.lines()
.dropWhile(line -> !line.equals("Room 1"))
.skip(1)
.takeWhile(line -> !line.equals("Room_end"))
.collect(Collectors.toList());
} catch (IOException ie) {
System.out.println("Unable to create " + fileName + ": " + ie.getMessage());
ie.printStackTrace();
}
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i).getname());//error on getname because it cant work with Strings
}
}
class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am able to get a method to print all Strings of the file but not specific range of Strings. I also tried to work with Stream. My code feel quite messy, but I've been working on it for a while an it seems it only get messier.
I think there is a problem if you want to use lambda expression here:
lambda expressions are functional programming, and functional programming requires immutability, that means there should not be state related issue, you can call the function and give it same parameters and the result always will be the same, but in your case, there should be a state indicating whether you should print the line or not.
can you try this solution? I write it in python, but mainly it is just about a variable should_print that located outside of the scope
should_print = False
result = reader.lines()
for line in result:
if line == "Room end":
break
if should_print:
print(line)
if line == "Room 1":
should_print = True
keep a boolean value outside of the iteration, and check/update the value in each iteration
public static Map<String, List<String>> getRooms(String path) throws IOException {
Map<String, List<String>> result = new HashMap<>();
try (Scanner sc = new Scanner(new File(path))) {
sc.useDelimiter("(?=Room \\d+)|Room_end");
while (sc.hasNext()) {
Scanner lines = new Scanner(sc.next());
String room = lines.nextLine().trim();
List<String> roomFeatures = new ArrayList<>();
while (lines.hasNextLine()) {
roomFeatures.add(lines.nextLine());
}
if (room.length() > 0) {
result.put(room, roomFeatures);
}
}
}
return result;
}
is one way of doing it for your 'rooms file' though it should really be made more OO by making a Room bean to hold the data. Output with your file: {Room 2=[Coffee, Iron ], Room 1=[Coffee, Iron, Microwave]}
Switched my code and used this:
private static String loadRoom(String fileName) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null; //we start with empty info
String ls = System.getProperty("line.separator"); //make a new line
while ((line = reader.readLine()) != null) { //consider if the line is empty or not
if (line.equals("Room 1")) { //condition start on the first line being "Room 1"
line = reader.readLine(); // read the next line, "Room 1" not added to stringBuilder
while (!line.equals("Room_end")) { //check if line String is "Room_end"
stringBuilder.append(line);//add line to stringBuilder
stringBuilder.append(ls);//Change Line in stringBuilder
line = reader.readLine();// read next line
}
}
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
Here's a solution that uses a scanner and a flag. You may choose to break the loop when it reads "Room_end"
import java.util.Scanner;
import java.io.*;
public class Main{
private static String loadRoom(String fileName) throws IOException {
Scanner s = new Scanner(new File(fileName));
StringBuilder sb = new StringBuilder();
boolean print = false;
while(s.hasNextLine()){
String line = s.nextLine();
if (line.equals("Room 1")) print = true;
else if (line.equals("Room_end")) print = false;
else if (print) sb.append(line).append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
try {
String content = loadRoom("content.txt");
System.out.println(content);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}

Remove a last blank line

I have a problem with some java code.
I'm returning a text from a method, which is on a .txt file. Then, I'm storing this text to a variable "text" and writing this on another .txt file. But the problem is: this new .txt file gets a new blank line at the bottom. That's because inside my method read, the variable "text" is receiving a "\n". How can I solve this problem?
PS: I'm doing this with educational purposes.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
public class Arquivo {
public static void main(String[] args) {
String text = read("in.txt");
write(text, "out.txt");
System.out.println("Text created!");
}
public static String read(String arquivo) {
String text = "";
try (BufferedReader br = new BufferedReader(new FileReader(arquivo))) {
String line = br.readLine();
while (line != null) {
text += line + "\n";
line = br.readLine();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
return text;
}
public static void write(String text, String arquivo) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(arquivo))) {
bw.write(text);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
My two created files "in.txt" and "out.txt".
this is
a text file.
this is
a text file.
(blank line)
please try this:
String line = br.readLine();
while (line != null) {
text += line;
line = br.readLine();
if (line!=null){
text += "\n";
}
}
you can try this variant:
String line;
while((line = br.readLine()) != null) {
text += line;
if (line!=null){
text += "\n";
}
}
A good solution to this type of problem is to add the newline before you write each additional line:
String line = br.readLine();
text += line;
while ((line = br.readLine()) != null) {
text = "\n" + line;
}
This way, you only add the newline for each additional line you write (no extraneous ones at the end). Notice the assignment (plus null check) in the while loop).
replace write(text, "out.txt"); with
write(text.substring(0,text.length()-1), "out.txt");
which will remove the last character, which is the /n before writing.
Store all the strings in a list, then join on the line feed
public static void main( String[] args ) {
String text = read( "in.txt" );
write( text, "out.txt" );
System.out.println( "Text created!" );
}
public static String read( String arquivo ) {
List<String> texts = new ArrayList<>();
try ( BufferedReader br = new BufferedReader( new FileReader( arquivo ) ) ) {
String line = br.readLine();
while ( line != null ) {
texts.add( line );
line = br.readLine();
}
} catch ( IOException e ) {
System.err.println( e.getMessage() );
}
return texts.stream().collect( Collectors.joining( "\n" ) );
}
public static void write( String text, String arquivo ) {
try ( BufferedWriter bw = new BufferedWriter( new FileWriter( arquivo ) ) ) {
bw.write( text );
} catch ( IOException e ) {
System.err.println( e.getMessage() );
}
}
String.trim()
public String trim()
Returns a copy of the string, with leading and
trailing whitespace omitted. If this String object represents an empty
character sequence, or the first and last characters of character
sequence represented by this String object both have codes greater
than '\u0020' (the space character), then a reference to this String
object is returned.
Otherwise, if there is no character with a code greater than '\u0020'
in the string, then a new String object representing an empty string
is created and returned.
Otherwise, let k be the index of the first character in the string
whose code is greater than '\u0020', and let m be the index of the
last character in the string whose code is greater than '\u0020'. A
new String object is created, representing the substring of this
string that begins with the character at index k and ends with the
character at index m-that is, the result of this.substring(k, m+1).
This method may be used to trim whitespace (as defined above) from the
beginning and end of a string.
Returns: A copy of this string with leading and trailing white space
removed, or this string if it has no leading or trailing white space.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
Simply trim the string before you return it from read.
public static String read(String arquivo) {
String text = "";
try (BufferedReader br = new BufferedReader(new FileReader(arquivo))) {
String line = br.readLine();
while (line != null) {
text += line + "\n";
line = br.readLine();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
return text.trim();
}
Just do not add \n before the last line:
String text = "";
...
String line = br.readLine();
boolean addNewLine = false;
while (line != null) {
if (addNewLine) {
text += "\n";
} else {
addNewLine = true;
}
text += line;
line = br.readLine();
}
Also, for performance improvement, consider using a StringBuilder instead of the string concatenation:
StringBuilder sb = new StringBuilder();
...
String line = br.readLine();
boolean addNewLine = false;
while (line != null) {
if (addNewLine) {
sb.append('\n');
} else {
addNewLine = true;
}
sb.append(line);
line = br.readLine();
}
...
String text = sb.toString();

How to search string in a file and then search that string in another file

I'm trying to create a java program that can read a file named file1.txt and store its strings and search those strings to another file named file2.txt and if the match is not found then print that particular string from file1.txt.
public static void main(String[] args)
{
try
{
BufferedReader word_list = new BufferedReader(new FileReader("file1.txt"));
BufferedReader eng_dict = new BufferedReader(new FileReader("file2.txt"));
String spelling_word = word_list.readLine();
String eng_dict_word = eng_dict.readLine();
while (spelling_word != null)
{
System.out.println(spelling_word);
spelling_word = word_list.readLine();
if(eng_dict_word.contains(spelling_word))
{
System.out.println("Word found "+spelling_word);
}
else
{
System.out.println("Word not found "+spelling_word);
}
}
word_list.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Right now I'm able to get data from file1.txt but unable to search file1's data for example to search word "Home" in file2.txt
See that here File1.txt contains Homee and File2.txt has Home, so Homee should be print
first, you need to read first file. Preferably to SET() as it will get rid of duplicate strings. You will have set1
When this is done, you need to read second file, and do the same. You will get set2
Now, you have need to use RemoveAll() method on set1 with set2 as parameter.
What is remaining in set1 needs to be printed on scren. You can do it with lambda.
See THIS to get how to read file.
see code below:
Set<String> set1 = new HashSet<>();
Set<String> set2 = new HashSet<>();
try (FileReader reader = new FileReader("file1.txt");
BufferedReader br = new BufferedReader(reader)) {
// read line by line
String line;
while ((line = br.readLine()) != null) {
set1.add(line);
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
try (FileReader reader = new FileReader("file2.txt");
BufferedReader br = new BufferedReader(reader)) {
// read line by line
String line;
while ((line = br.readLine()) != null) {
set2.add(line);
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
set1.removeAll(set2);
set1.forEach(System.out::println);
Use Regex for the specific need, below is the refactored code for your problem. Let me know if this works for you.
public static void main(String[] args) throws IOException
{
try
{
BufferedReader word_list = new BufferedReader(new FileReader("resources/file1.txt"));
BufferedReader eng_dict = new BufferedReader(new FileReader("resources/file2.txt"));
String spelling_word = word_list.readLine();
String eng_dict_word = eng_dict.readLine();
int matchFound = 0;
Matcher m = null;
while (spelling_word != null)
{
// creating the pattern for checking for the exact match on file2.txt
String spelling_word_pattern = "\\b" + spelling_word + "\\b";
Pattern p = Pattern.compile(spelling_word_pattern);
while(eng_dict_word !=null) {
m = p.matcher(eng_dict_word);
if(m.find()) {
matchFound = 1;
break;
}
eng_dict_word = eng_dict.readLine();
}
if(matchFound == 1) {
System.out.println("Word found " + m.group());
}else {
System.out.println("Word not found "+ spelling_word);
}
spelling_word = word_list.readLine();
eng_dict = new BufferedReader(new FileReader("resources/file2.txt"));
eng_dict_word = eng_dict.readLine();
matchFound = 0;
}
word_list.close();
eng_dict.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
file1.txt content
Homeee
Ho
hello
hom
xx
Me
file2.txt content
Home
Me
H
Homey
Result
Word not found Homeee
Word not found Ho
Word not found hello
Word not found hom
Word not found xx
Word found Me

JAVA : file I/O

I have got two text files with data in the following format
data.txt file as following format
A 10
B 20
C 15
data1.txt file is in format (start node,end node, distance):
A B 5
A C 10
B C 20
I am trying to implement a search strategy, for that I need to load the data from data.txt and ONLY the start node and end node from data1.txt (i.e. I dont need the distance). I need to store this information in a stack as I think it would be a best data structure for implementing greedy search.
Actually I am not sure how to get started with file I/O to read these files and store them in array to implement greedy search. So I would highly appreciate any starting idea on how to proceed.
I am new to this, so please bear with me. Any help is much appreciated. Thanks.
EDIT:
Here is what I have got till now
String heuristic_file = "data.txt";
try
{
FileReader inputHeuristic = new FileReader(heuristic_file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
while ((line = bufferReader.readLine()) != null)
{
System.out.println(line);
}
bufferReader.close();
} catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
My approach, doesn't differ fundamentally from the others. Please regard the try/catch/finally blocks. Always put the closing statements into the finally block, so the opened file is guaranteed to be closed, even if an exception was thrown while reading the file.
The part between the two //[...] could surely be done more efficient. Maybe reading the whole file in one take and then parsing the text backwards and searching for a line-break? Maybe a Stream-API supports to set the reading position. I honestly don't know. I didn't need that, up to now.
I chose to use the verbose initialization of the BufferedReader, because then you can specify the expected encoding of the file. In your case it doesn't matter, since your files do not contain symbols out of the standard ASCII range, but I believe it's a semi-best-practice.
Before you ask: r.close() takes care of closing the underlying InputStreamReader and FileInputStream in the right order, till all readers and streams are closed.
public static void readDataFile(String dir, String file1, String file2)
throws IOException
{
File datafile1 = new File(dir, file1);
File datafile2 = new File(dir, file2);
if (datafile1.exists())
{
BufferedReader r = null;
try
{
r = new BufferedReader(
new InputStreamReader(
new FileInputStream(datafile1),
"UTF-8"
)
);
String row;
Stack<Object[]> s = new Stack<Object[]>();
String[] pair;
Integer datapoint;
while((row = r.readLine()) != null)
{
if (row != null && row.trim().length() > 0)
{
// You could use " " instead of "\\s"
// but the latter regular expression
// shorthand-character-class will
// split the row on tab-symbols, too
pair = row.split("\\s");
if (pair != null && pair.length == 2)
{
datapoint = null;
try
{
datapoint = Integer.parseInt(pair[1], 10);
}
catch(NumberFormatException f) { }
// Later you can validate datapairs
// by using
// if (s.pop()[1] != null)
s.add(new Object[] { pair[0], datapoint});
}
}
}
}
catch (UnsupportedEncodingException e1) { }
catch (FileNotFoundException e2) { }
catch (IOException e3) { }
finally
{
if (r != null) r.close();
}
}
// Do something similar with datafile2
if (datafile2.exists())
{
// [...do the same as in the first try/catch block...]
String firstrow = null, lastrow = null;
String row = null;
int i = 0;
do
{
lastrow = row;
row = r.readLine();
if (i == 0)
firstrow = row;
i++;
} while(row != null);
// [...parse firstrow and lastrow into a datastructure...]
}
}
use split
while ((line = bufferReader.readLine()) != null)
{
String[] tokens = line.split(" ");
System.out.println(line + " -> [" + tokens[0] + "]" + "[" + tokens[1] + "][" + tokens[2] + "]");
}
if you must have this in an array you can use the following:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
public class NodeTest {
public static void main(String[] args) throws ParseException {
try {
File first = new File("data.txt");
File second = new File("data1.txt");
Node[] nodes1 = getNodes(first);
Node[] nodes2 = getNodes(second);
print(nodes1);
print(nodes2);
}
catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
}
public static final void print(Node[] nodes) {
System.out.println("======================");
for(Node node : nodes) {
System.out.println(node);
}
System.out.println("======================");
}
public static final Node[] getNodes(File file) throws IOException {
FileReader inputHeuristic = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
List<Node> list = new ArrayList<Node>();
while ((line = bufferReader.readLine()) != null) {
String[] tokens = line.split(" ");
list.add(new Node(tokens[0], tokens[1]));
}
bufferReader.close();
return list.toArray(new Node[list.size()]);
}
}
class Node {
String start;
String end;
public Node(String start, String end){
this.start = start;
this.end = end;
}
public String toString() {
return "[" + start + "][" + end + "]";
}
}
Something like this?
HashSet<String> nodes = new HashSet<String>();
try(BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
nodes.add(l[0]);
line = br.readLine();
}
}
try(BufferedReader br = new BufferedReader(new FileReader("data1.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
if (nodes.contains(l[0]) || nodes.contains(l[1]))
// Do whatever you want ...
line = br.readLine();
}
}

Reading from two files at the same time

Suppose we have two files as f1 and f2.
Also suppose that there is a function named comparision(File f1,File f2).
This function will get the two files as arguments and take the first character(word) from f1 and compare it with all the characters in the f2 until the end, picking second ones and doing it until end as first and etc.
My question is: How can I implement this? Do I need to know the EOF ? And if so, how to get it?
Assume that files are plain text (.txt) and every word is in one line.
as an example:
f1:
I
am
new
to
java
f2:
java
is
a
programing
language
Here's the code:
static void comparision(File f, File g) throws Exception
{
Set<String> text = new LinkedHashSet<String>();
BufferedReader br = new BufferedReader(new FileReader(g));
for(String line;(line = br.readLine()) != null;)
text.add(line.trim().toString());
if(text==null)
return;
BufferedReader br = new BufferedReader(new FileReader(f));
String keyword = br.readLine();
if (keyword != null) {
Pattern p = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
StringBuffer test = new StringBuffer(text.toString());
matcher = p.matcher(test);
if (!matcher.hitEnd()) {
total++;
if (matcher.find()) {
//do sth
}
}
}
}
edit by jcolebrand
Something to think about, we need program flow that looks like this (psuedocode)
function(file1,file2) throws exceptions{
ArrayList<string> list1, list2; //somebody said we should use an ArrayList ;-)
string readinTempValue = null;
br = BufferedReader(file1) //we are already using a BufferredReader
readinTempValue = br.ReadLine();
//this is a loop structure
while (readinTempValue != null){ //trust me on this one
//we need to get the string into the array list....
//how can we ADD the value to list1
readinTempValue = br.ReadLine(); //trust me on this one
}
br = BufferedReader(file2) //we are already using a BufferredReader
readinTempValue = br.ReadLine();
//this is a loop structure
while (readinTempValue != null){ //trust me on this one
//we need to get the string into the array list....
//how can we ADD the value to list2
readinTempValue = br.ReadLine(); //trust me on this one
}
foreach(value in list1){
foreach(value in list2){
compare value from list 1 to value from list 2
}
}
}
Simple basic algorithm (can be fine tuned based upon WHY you want to compare)
Read the second file and create a HashSet "hs"
for each word "w" in file 1
if(hs.contains(w))
{
w is present in the second file
}
else
{
w is not present in the second file
}
modifications to OP's code
static int comparision(File f, File g) throws Exception
{
int occurences = -1;
Set<String> text = new HashSet<String>();
BufferedReader br = new BufferedReader(new FileReader(g));
String line = br.readLine();
while (line != null)
{
String trimmedLine = line.trim();
if (trimmedLine.length() > 0)
{
text.add(trimmedLine.toString());
}
line = br.readLine();
}
if (text.isEmpty())
{
// file 1 doesn't contain any useful data
return -1;
}
br = new BufferedReader(new FileReader(f));
String keyword = br.readLine();
if (keyword != null)
{
String trimmedKeyword = keyword.trim();
if (trimmedKeyword.length() > 0)
{
if (text.contains(trimmedKeyword))
{
occurences++;
}
}
line = br.readLine();
}
return occurences;
}

Categories