check if a value exists in an external file (java) - 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);
}

Related

Finding a line that contain a string using contains method

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);

reading input from file until specific word is read

i am writing a java program to read a file and print output to another string variable.which is working perfectly as intended using is code.
{
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
}
System.out.println(key); //this prints contents of .txt file
}
this prints whole text in the file.But i want to only print the lines till word END is encountered in file.
example: if input.txt file contains following text : this test file END extra in
it should print only :
this test file
Just do a simple indexOf to see where it is and if it exists in the line. If the instance is found one option would be using substring to cut off everything up until the index of the keyword. For a bit more control though try using java regular expressions.
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while ((line = reader.readLine()) != null && line.indexOf("Keyword to look for") == -1)
key += line;
System.out.println(key);
I am not sure why it needs to be any more complicated than this:
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = re.readLine();
if (str.equals("exit")) break;
// whatever other code.
}
You can do it in many ways. one of them is using indexOf method to specify the start index of "END" in input and then using subString method.
for more information, read documentation of String calss. HERE
This will work for your issue.
public static void main(String[] args) throws IOException {
String key = "";
FileReader file = new FileReader("/home/halil/khalil.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
} String output = "";
if(key.contains("END")) {
output = key.split("END")[0];
System.out.println(output);
}
}
You have to change your logic to check if the line contains "END".
If END not found in a line, add the line to key stringin your program
If yes, split that line into word array, read the line till you encounter the word "END" and append it to your key string. Consider using Stringbuilder for key.
while (line != null) {
line = reader.readLine();
if(!line.contains("END")){
key += line;
}else{
//Note that you can use split logic like below, or use java substring
String[] words = line.split("");
for(String s : words){
if(s.equals("END")){
return key;
}
key += s;
}
}
}

Delete multiple lines from text file

I am trying to create a method to delete some of the text from my txt file. I started by checking if a string that I have exist in the file:
public boolean ifConfigurationExists(String pathofFile, String configurationString)
{
Scanner scanner=new Scanner(pathofFile);
List<String> list=new ArrayList<>();
while(scanner.hasNextLine())
{
list.add(scanner.nextLine());
}
if(list.contains(configurationString))
{
return true;
}
else
{
return false;
}
}
Since the string I want to delete contains multiple lines (String configurationString = "This\nis a\n multiple lines\n string";) I started by creating a new array of strings and splitting the string into array members.
public boolean deleteCurrentConfiguration(String pathofFile, String configurationString)
{
String textStr[] = configurationString.split("\\r\\n|\\n|\\r");
File inputFile = new File(pathofFile);
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(textStr[0])) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
return true;
}
Can someone please help on how to delete the string from the txt file and also the line before and after the string?
There are many different ways to do this, though one way I do it is to firstly read the files content into an array of Strings by line (looks like you already did this), then to remove the data you don't want, and write to the file line-by-line the new information you do want.
To remove lines before the line you don't want, the line you don't want, and the line after you don't want, you could something like this:
List<String> newLines=new ArrayList<>();
boolean lineRemoved = false;
for (int i=0, i < lines.length; i++) {
if (i < lines.length-1 && lines.get(i+1).equals(lineToRemove)) {
// this is the line before it
} else if (lines.get(i).equals(lineToRemove)) {
// this is the line itself
lineRemoved = true;
} else if (lineRemoved == true) {
// this is the line after the line you want to remove
lineRemoved = false; // set back to false so you don't remove every line after the one you want
} else
newLines.add(lines.get(i));
}
// now write newLines to file
Note that this code is rough and untested, but should get you where you need to be.

Reading the first line of a text file in Android Java(API17)

I'm really new in Java and I'm trying to figure out how to read a line from .txt file in SD card. The code below doesn't seem to work since it returns an empty result.
public static final String filePath = Environment.getExternalStorageDirectory().getPath();
public static String getProfileInfo() {
String line = "";
StringBuilder sb = new StringBuilder();
try{
File unzippedText = new File(filePath + "profile.txt");
BufferedReader text = new BufferedReader(new FileReader(unzippedText));
sb.append(line);
text.close();
}catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}
Thanks
This code is not going to do anything
sb.append(line);
line is still equal to ""
try reading using the BufferedReader.readLine
line = text.readLine (); // first line only

Check if a string/line that is going to write into a text file is already exist in the text file

I am analyzing a web access log and try to find out all the unique object (any file or any path) that were requested only once in the access log. Every time the program write into the text file, the content of the text file looks like this :
/~scottp/publish.html
/~ladd/ostriches.html
/~scottp/publish.html
/~lowey/
/~lowey/kevin.gif
/~friesend/tolkien/rootpage.html
/~scottp/free.html
/~friesend/tolkien/rootpage.html
.
.
.
I want to check if the line which is going to write into the text file is already exist in the text file. In order words, if it's does exist in the text file, then do nothing and skip it and analyze the next line. If not, then write it into the text file.
I tried to use equals or contains but it doesn't seems to be work, here's a little pieces of my code:
// Find Unique Object that were requested only once
if (matcher3.find()) {
if(!requestFileName.equals(bw.equals(requestFileName))) {
bw.write(requestFileName);
bw.newLine();
}
}
What should I do to actually perform a check ?
As #JB Nizet commented you should make use of Set
Set<String> set = new HashSet<String>();
BufferedReader reader = new BufferedReader(new FileReader(new File("/path/to/yourFile.txt")));
String line;
while((line = reader.readLine()) != null) {
// duplicate
if(set.contains(line))
continue;
set.add(line);
// do your work here
}
Perhaps something simple like this:
try (BufferedReader br = new BufferedReader(new FileReader(yourFilePath))) {
boolean lineExists = false;
String currentLine;
while ((currentLine = br.readLine()) != null) {
if (currentLine.trim().equalsIgnoreCase(requestFileName.trim())) {
lineExists = true;
break;
}
}
br.close();
if (!lineExists) {
bw.write(requestFileName);
bw.newLine();
}
}
catch (IOException e) {
// Do what you want with Exception...
}

Categories

Resources