CTRL +F Logic in java - java

I want to search the specific word in the text file and store that word in the array list. I have done like this but it gives output like word exist in the text file or not. I want to store that text in the array list
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
List<String> searchedWords = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
if(!searchedWords.contains(word)){
searchedWords.add(word);
}
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("Words that you have searched and found:");
for(String word : searchedWords){
System.out.println(word);
}
You will have an arraylist searchedWords which will keep track of the searched words, you will notice that the if statement will not allow duplicates in the arraylist, so if you want to allow duplicates just remove the if(!searchedWords.contains(word)) and just write searchedWords.add(word);.

You can define a String ArrayList with your other declarations using:
ArrayList<String> matches = new ArrayList<String>();
Then when you find a word that matches, add it to the ArrayList using:
matches.add(word);
Edit:
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
ArrayList<String> matches = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
matches.add(word);
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Related

Find a word and return specific value of the word

I have a file with this content:
1.10.100.1 1000.0
1.10.100.2 2000.0
1.10.100.3 2000.0
1.10.500.4 1000.0
i wrote the function that find the specific string in the file:
public double searchInBalance(String depositNumber) {
try {
String[] words = null;
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string;
String inputBalanceToFind = depositNumber;
while ((string = bufferedReader.readLine()) != null) {
words = string.split(" ");
for (String word : words) {
if (word.equals(inputBalanceToFind)) {
System.out.println("string :" + string);
}
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in searchInBalance");
}
return 1;
}
i want to make a function that when find the left value of the file return the right value(the double value) back but have no idea how to do that please help me
public double searchInBalance(String depositNumber){
try {
String[] words = null;
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string;
String inputBalanceToFind = depositNumber;
while ((string = bufferedReader.readLine()) != null) {
words = string.split(" ");
for (int i = 1; i < words.length; i += 2) {
if (words[i].equals(inputBalanceToFind)) {
System.out.println(words[i]+" - "+words[i - 1]);
}
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in searchInBalance");
}
}
Just make a for loop with a counter to work with the indexes of the Array. But this is not a good programming style and you should try to improve your solution :D

how to copy only a part of .CSV based on first column elements with java

copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}

Add two csv file to a list in Java

My Java program has a superclass (ProgettoBase) and two underclasses (ProgettoCorpo and ProgettoOre). I must copy two different csv files (progetti_ora.csv and progetti_corpo.csv) to a list but I can't see the elements of the list when I launch the program.
public void readFile () {
List<String> projects = new ArrayList<>();
System.out.println("My list is: " + projects);
//read 1 progetti_ora
String csvFile = "progetti_ora.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
//read 2 progetti_corpo
String csvFileDue = "progetti_corpo.csv";
BufferedReader brDue = null;
String lineDue = "";
String cvsSplitByDue = ";";
//read file 1
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] vote = line.split(cvsSplitBy);
for(String s : vote)
System.out.println("List one: " + s);
for(int x = 0; x <= 2; x++) {
projects.add(vote[x].toString());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("OK1");
//read file 2
try {
brDue = new BufferedReader(new FileReader(csvFileDue));
while ((lineDue = brDue.readLine()) != null) {
String[] voteDue = lineDue.split(cvsSplitByDue);
for(String t : voteDue)
System.out.println("Lista file due: " + t);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("OK2");
}

To print the given rows of string into columns

I have *.txt file with first row as name,address,mail id and second line with the values. I have to print this into two columns,the first one with the headings and second with the value using Java. how do I do this?
public class ReadFile1 {
public static void main(String[] args) {
BufferedReader br=null;
String sCurrentLine = null;
String delimiter = ",";
String[] filetags;
try {
br = new BufferedReader(new FileReader("path\\Read.txt"));
sCurrentLine = br.readLine();
StringBuffer result = new StringBuffer();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
filetags = line.split(delimiter);
for(int i = 0;i < line.length(); i++)
{
System.out.println("****" +sCurrentLine);
String[] s = line.split(",");
for(int j = i-1; j<line.length();j++)
{
System.out.println("##############"+Arrays.toString(s));
}
}
}
}
This is what I tried. Ex: I have a file say,
line1) name,email,mobile and second
line2) john,j#abc.com,9876
line3) max,max#xyz.com,1234
Now, I need to print:
name john
email john#abc.com
moblie 9876
name max
email max#xyz.com
mobile 1234
Below is one way you may be able to get what you want, It is similar to how you have attempted but slightly more refined.
The File:
name,email,mobile and second
john,j#abc.com,9876
max,max#xyz.com,1234
The code:
//File is on my Desktop
Path myFile = Paths.get(System.getProperty("user.home")).resolve("Desktop").resolve("tester.txt");
//Try-With-Resources so we autoclose the reader after try block
try(BufferedReader reader = new BufferedReader(new FileReader(myFile.toFile()))){
String[] headings = reader.readLine().split(",");//Reads First line and gets headings
String line;
while((line = reader.readLine()) != null){//While there are more lines
String[] values = line.split(","); //Get the values
for(int i = 0; i < values.length; i++){//For each value
System.out.println(headings[i] + ": " + values[i]);//Print with a heading
}
}
} catch (IOException io) {
io.printStackTrace();
}
Good Luck!
Something like this should do the trick.
Read the file and store each line in a list.
Iterate through the list of lines
If it is safe to assume the first line will always be the title line, take the input and store it in a collection.
For the rest of the lines, split on the comma and use the index of the splitter array to refer to the title column.
List <String> lines = new ArrayList<String>();
Scanner scanner = new Scanner(new File("FileName.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
lines.add(line);
}
scanner.close();
int lineNo = 0;
List <String> title = new ArrayList<String>();
for(String line : lines){
if(lineNo == 0){
String [] titles = line.split(",");
for(String t : titles){
title.add(t);
}
lineNo++;
}
else{
String input = line.split(",");
for(int i = 0; i<input.length; i++){
System.out.println(title.get(i) + ": " + input[i]);
}
lineNo++;
}
}

Stuck in while loop with BufferedReader-java

I'm completely at a lose for why this isn't working. I've had similar loops before and they've worked fine.
try{
text = new BufferedReader(new FileReader(fileName));
while ((lineOfText = text.readLine()) != null){
StringTokenizer tokens = new StringTokenizer(lineOfText," , .;:\"&!?-_\n\t12345678910[]{}()##$%^*/+-");
while (tokens.hasMoreTokens()){
countTotalWordsInDocument++;
String word = tokens.nextToken();
countTotalCharactersInAllWords = countTotalCharactersInAllWords + word.length();
}
}
text.close();
} catch (IOException e) {
System.out.println("file not found");
}

Categories