fetching value for given string - java

I want to search for a string and fetch the value for that string in a file .
For example file contains something like this
test=1
test2=2
if search string str="test2" is given then it should return value 2 .
Sample code i have tried is
public class ScannerExample {
public static void main(String args[]) throws FileNotFoundException {
//creating File instance to reference text file in Java
String filePath = "c:/temp/test.txt";
//Creating Scanner instnace to read File in Java
String str = "text";
//Reading each line of file using Scanner class
BufferedReader br = new BufferedReader(new FileReader(filePath));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.contains(str)) {
result=true;
System.out.println("Found entry ");
break;
}
}
}
}
here I am check if value exists or not .please suggest some method to fetch its value
sample.txt:
test=1
test2=2
testnew=new
testold=old2

Simply use a Properties object and load the file with it
Properties p = new Properties();
try (Reader reader = new FileReader(filePath)) {
// Load the file
p.load(reader);
}
// Print the value of the parameter test2
System.out.println(p.getProperty("test2"));

You can split and get the value.
String[] splits = sCurrentLine.split("=");
System.out.println("Value is " + splits[1])
and will contain the value.

You can do it in couple of ways:
Way 1:
Read File line by line and split each line by = and use left part as key and right part as value. Put them in a HashMap. While doing look up read it from HashMap on basis of key.
Way 2:
In your current approach, split each line by = and match entered key with left part if it matches return right part.
Hope this helps.

Related

Java read input/output print duplicate string to file

Hi I am working on this problem, Suppose a library is processing an input file containing the titles of books in order to identify duplicates. Write a program that reads all of the titles from an input file called bookTitles.inp and writes them to an output file called duplicateTitles.out. When complete, the output file should contain all titles that are duplicated in the input file. Note that the duplicate titles should be written once, even though the input file may
contain same titles multiple times. If there are not duplicate titles in the input file, the output file should be empty. Create the input file using Notepad or another text editor, with one title per line. Make sure you have a number of duplicates, including some with three or more copies.
So far I have this but It is printing the duplicates more than once if I change the order of the input file. Thanks.
import java.io.*;
public class Library
{
public static void main(String[] args) throws IOException
{
String line3="";
boolean dup = false;
// PrintWriter object for output.txt
PrintWriter pw = new PrintWriter("C:\\Users\\Ilyas\\Desktop\\tempBookTitles.txt");
PrintWriter pw2 = new PrintWriter("C:\\Users\\Ilyas\\Desktop\\duplicateTitles.txt");
// BufferedReader object for input.txt
BufferedReader br1 = new BufferedReader(new
FileReader("C:\\Users\\Ilyas\\Desktop\\bookTitles.txt")); //read input file
String line1 = br1.readLine();
// loop for each line of input.txt
while(line1 != null)
{
boolean flag = false;
// BufferedReader object for output.txt
BufferedReader br2 = new BufferedReader(new
FileReader("C:\\Users\\Ilyas\\Desktop\\tempBookTitles.txt"));
BufferedReader br3 = new BufferedReader(new
FileReader("C:\\Users\\Ilyas\\Desktop\\duplicateTitles.txt")); //try
String line2 = br2.readLine();
// loop for each line of output.txt
while(line2 != null)
{
if(line1.equals(line2))
{
line3 = br3.readLine();
flag = true;
if(line1.equals(line3))
{
line1 = null;
}
else
{
pw2.println(line1);
pw2.flush();
//break;
}
}
}
line2 = br2.readLine();
}
// if flag = false
// write line of input.txt to output.txt
if(flag==false)
{
pw.println(line1); //print to temp file, delete temp file at end
pw.flush();
}
line1 = br1.readLine();
}
br1.close();
pw.close();
pw2.close();
System.out.println("File operation performed successfully");
}
}
You should try to make the program readable, and also make it smaller by breaking into chunks of methods.
See my suggestion below.
private List<String> getAllTitles(String filepath){
List<String> titles = new ArrayList<>();
// read the file,
// for each of the titles, insert into the list
return titles;
}
private Set<String> getDuplicates(List<String> titles){
Set<String> alreadyReadSet = new HashSet<>();
Set<String> duplicateSet = new HashSet<>();
for (String title : titles) {
if(/*alreadyReadSet contains the title*/){
// put title into duplicateList
}
// put the title into alreadyReadSet
}
return duplicateSet;
}
private void printDuplicateList(Collection<String> duplicateList){
// print to a file
}
To solve it without maps, you can use method contains, instead of writing directly to output file, create a output variable String, and change
{
pw2.println(line1);
pw2.flush();
}
for
if (!output.contains(line1+"\n"))
output=output + line1+"\n"
and after the loop print output to the file
So I am sure you have solved your problem by now, but in case anyone else comes across this thread looking for advice...
I encountered this same problem in my schoolwork recently and it drove me nuts trying to solve it with the tools we had learned so far in the course (which did not include maps or ArrayList). I ended up looking into the documentation for BufferedReader; and using the mark(int readLimit) and reset() methods. I got 100% on the assignment, so I thought I would leave this tip here for others.

How to replace specific String in a text file by java?

I'm writing a program with a text file in java, what I need to do is to modify the specific string in the file.
For example, the file has a line(the file contains many lines)like "username,password,e,d,b,c,a"
And I want to modify it to "username,password,f,e,d,b,c"
I have searched much but found nothing. How to deal with that?
In general you can do it in 3 steps:
Read file and store it in String
Change the String as you need (your "username,password..." modification)
Write the String to a file
You can search for instruction of every step at Stackoverflow.
Here is a possible solution working directly on the Stream:
public static void main(String[] args) throws IOException {
String inputFile = "C:\\Users\\geheim\\Desktop\\lines.txt";
String outputFile = "C:\\Users\\geheim\\Desktop\\lines_new.txt";
try (Stream<String> stream = Files.lines(Paths.get(inputFile));
FileOutputStream fop = new FileOutputStream(new File(outputFile))) {
stream.map(line -> line += " manipulate line as required\n").forEach(line -> {
try {
fop.write(line.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
You can try like this:
First, read the file line by line and check each line if the string you want to replace exists in that, replace it, and write the content in another file. Do it until you reach EOF.
import java.io.*;
public class Files {
void replace(String stringToReplace, String replaceWith) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("/home/asn/Desktop/All.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("/home/asn/Desktop/All-copy.txt"));
String line;
while((line=in.readLine())!=null) {
if (line.contains(stringToReplace))
line = line.replace(stringToReplace, replaceWith);
out.write(line);
out.newLine();
}
in.close();
out.close();
}
public static void main(String[] args) throws IOException {
Files f = new Files();
f.replace("amount", "####");
}
}
If you want to use the same file store the content in a buffer(String array or List) and then write the content of the buffer in the same file.
If your file look similar to this:
username:username123,
password:password123,
After load file to String you can do something like this:
int startPosition = file.indexOf("username") + 8; //+8 is length of username with colon
String username;
for(int i=startPosition; i<file.length(); i++) {
if(file.charAt(i) != ',') {
username += Character.toString(file.charAt(i));
} else {
break;
}
System.out.println(username); //should prong username
}
After edit all thing you want to edit, save edited string to file.
There are much ways to solve this issue. Read String docs to get to know operations on String. Without your code we cannot help you enough aptly.
The algorithm is as follows:
Open a temporary file to save edited copy.
Read input file line by line.
Check if the current line needs to be replaced
Various methods of String class may be used to do this:
equals: Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
equalsIgnoreCase: Compares this String to another String, ignoring case considerations.
contains: Returns true if and only if this string contains the specified sequence of char values.
matches (String regex): Tells whether or not this string matches the given regular expression.
startsWith: Tests if this string starts with the specified prefix (case sensitive).
endsWith: Tests if this string starts with the specified prefix (case sensitive).
There are other predicate functions: contentEquals, regionMatches
If the required condition is true, provide replacement for currentLine:
if (conditionMet) {
currentLine = "Your replacement";
}
Or use String methods replace/replaceFirst/replaceAll to replace the contents at once.
Write the current line to the output file.
Make sure the input and output files are closed when all lines are read from the input file.
Replace the input file with the output file (if needed, for example, if no change occurred, there's no need to replace).

Find a word in a File and print the line that contains it in java

Using command line, I am supposed to enter a file name that contains text and search for a specific word.
foobar file.txt
I started writing the following code:
import java.util.*;
import java.io.*;
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner (new File (args[1]) );
while (input.hasNext()) {
String x = input.nextLine();
}
}
}
My program is supposed to find word and then print the whole line that contains it.
Please be specific since I am new to java.
You are already reading in each line of the file, so using the String.contains() method will be your best solution
if (x.contains(word) ...
The contains() method simply returns true if the given String contains the character sequence (or String) you pass to it.
Note: This check is case sensitive, so if you want to check if the word exists with any mix of capitalization, just convert the strings to the same case first:
if (x.toLowerCase().contains(word.toLowerCase())) ...
So now here is a complete example:
public static void main(String[] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner(new File(args[1]));
// Let's loop through each line of the file
while (input.hasNext()) {
String line = input.nextLine();
// Now, check if this line contains our keyword. If it does, print the line
if (line.contains(word)) {
System.out.println(line);
}
}
}
Firest you have to open file and then read it line by line and check that word is in that line on not. see the code below.
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0]; // the word you want to find
try (BufferedReader br = new BufferedReader(new FileReader("foobar.txt"))) { // open file foobar.txt
String line;
while ((line = br.readLine()) != null) { //read file line by line in a loop
if(line.contains(word)) { // check if line contain that word then prints the line
System.out.println(line);
}
}
}
}
}

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

Trying to read in multiple lines of a file into string array depending on what the line starts with then enter into a map

Why do i only get one entry into the map when i run this code.There is thousands of lines in the file im reading in but it only seems to be getting to the first line and stopping?
public class Details {
public Map<String, String> dictionaryWords() throws IOException{
String cvsSplitBy = ",";
Collection<String> words = new TreeSet<String>();
Map<String,String> m = new TreeMap<String,String>();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("dictionary.csv")));
String line = null;
String [] word = null;
String remove = null;
String nextline = null;
String getAllLines = "-";
while ((line = br.readLine())!= null) {
if (line.startsWith("\"")) {
getAllLines = line;
while((nextline = br.readLine())!= null){
if(!nextline.startsWith("\"")){
getAllLines.concat(nextline);
}else{
}
words.add(getAllLines);
word = getAllLines.split(cvsSplitBy);
remove = word[0].replace('"', '-');
m.put(remove.toLowerCase(),Arrays.toString(word));
}
}else{
}
}
for (String key : m.keySet()) {
System.out.println(key + " " + m.get(key));}
return m;
}
Try the following code
if(!nextline.startsWith("\""))
{
getAllLines = getAllLines.concat(nextline);
}
Don't forget to reassign "getAllLines" to the return value of the .concat() function. Since Strings are immutable, the .concat() function returns a new String object, which you do not assign to anything (therefore it is lost). This leaves you with your original String still stored in "getAllLines" as if the call to .concat() was never made.
Feel Free to use the StringBuilder class and the append method, which will likely be much faster than creating new Strings via .concat() thousands of times.
Also: You do not need blank else{} statements.
In the following part of your code the nextlines (2nd ...) are lost in space. They are saved in the variable nextline and used as a parameter for getAllLines.concat. But the return value of String::concat is not assigned to anything.
...
while((nextline = br.readLine())!= null){
if(!nextline.startsWith("\"")){
getAllLines.concat(nextline);
}else{
...

Categories

Resources