Java Code check fields in duplicate, when value change start again - java

I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}

The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0

Related

Read csv row by row using java and concatenate as string

I have a CSV(2 columns) that has 1000 rows. The task I am working on is to retrieve a set of 100 first column rows and concatenate as a string( 'col1row1'+'col1row2'+'col1row3'+....+'col1row100' ). So this formatted string i will use as a parameter for a new function.
The following code only displays my CSV(having 2 columns) as an Array. Can someone help me here?
public static void main(String[] args) {
try {
String csvFile = "data.csv";
File file = new File(csvFile);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
String tempArr[] ;
br.readLine();
while((line = br.readLine()) != null) {
tempArr = line.split(" ");
System.out.print(Arrays.toString(tempArr) + " ");
}
br.close();
} catch(Exception ioe) {
ioe.printStackTrace();
}
}
String[] colArr= br. readLine(). split(" ");
String col1= colArr[0], col2=colArr[1];
while(...){
tempArr= line. split();
col1Str += col1 + tempArr[0];
col2Str += col2 + tempArr[1];
}

Java: Read file as long as a new date is found

I want to read the file and add each entry to an arraylist on a date. But the date should also be included.
File Example:
15.09.2002 Hello, this is the first entry.
\t this line, I also need in the first entry.
\t this line, I also need in the first entry.
\t this line, I also need in the first entry.
17.10.2020 And this ist the next entry
I tried this. But the Reader reads only the first Line
public class versuch1 {
public static void main(String[] args) {
ArrayList<String> liste = new ArrayList<String>();
String lastLine = "";
String str_all = "";
String currLine = "";
try {
FileReader fstream = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fstream);
while ((currLine = br.readLine()) != null) {
Pattern p = Pattern
.compile("[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2} [0-2]?[0-9]:[0-6]?[0-9]:[0-5]");
Matcher m = p.matcher(currLine);
if (m.find() == true) {
lastLine = currLine;
liste.add(lastLine);
} else if (m.find() == false) {
str_all = currLine + " " + lastLine;
liste.set((liste.indexOf(currLine)), str_all);
}
}
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.print(liste.get(0) + " "+liste.get(1);
}
}
I have solved my problem :)
public class versuch1 {
public static void main(String[] args) {
ArrayList<String> liste = new ArrayList<String>();
String lastLine = "";
String currLine = "";
String str_all = "";
try {
FileReader fstream = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fstream);
currLine = br.readLine();
while (currLine != null) {
Pattern p = Pattern
.compile("[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2} [0-2]?[0-9]:[0-6]?[0-9]:[0-5]");
Matcher m = p.matcher(currLine);
if (m.find() == true) {
liste.add(currLine);
lastLine = currLine;
} else if (m.find() == false) {
liste.set((liste.size() - 1), (str_all));
lastLine = str_all;
}
currLine = br.readLine();
str_all = lastLine + currLine;
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.print(liste.get(1) + " ");
}
}
While reading the lines, keep a "current entry".
If the line read begins with a date, then it belongs to a new entry. In this case add the current entry to the list of entries and create a new current entry consisting of the read line.
If the line did not begin with a date, just add it to the current entry.
For this to work, you need to read the first line into the current entry before the loop. And after the loop you need to add the current entry to the list of entries. This in turn only works if there is at least one line and the first line begins with a date. So handle the special case of no lines specially (use if-else). And report an error if the first line does not begin with a date.
Happy coding.

Count the lines of several methods but return separate values not the sum of all

I'm going to elabortate my question because I had a hard time labeling the question the right way.
I'm labeling my methods like this:
/*Start*/
public void contadorDeLineas(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
I have several methods labeled like that but I want to count them separately, but the code I wrote counts the lines inside the methods starting from public and finishing in "Finish". But as for now the code I wrote counts all the lines inside the methods and return the sum of all the lines. What I want to do is read the first block return that value and continue searching for the next block of code.
This is the code I wrote
public void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
while((line = br.readLine())!=null){
if(line.startsWith("/*St")){
do{
line = br.readLine();
line = line.trim();
System.out.println(line);
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
}
}
br.close();
System.out.println("Found: " + lines_inside);
}
This is an example of what my code is showing in the console
/*Start*/
public void LineMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
/*Start*/
public static void main(String[] args)throws IOException{
program2 test = new program2();
File root = new File(args[0]);
test.LOC(root);
System.out.println("Found: " + test.lines);
System.out.println("Other type of lines: " + test.toDo);
}
}
/*Finish*/
Block comments lines: 11
Instead I'm looking for a result like a first print showing the number 3 and then a number 8.
Any guidance will be appreciated.
Try this
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
boolean inside = false;
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains("/*Start*/")) {
inside = true;
count = 0;
} else if (line.contains("/*Finish*/")) {
System.out.println("Found: " + count);
inside = false;
} else if (inside) {
++count;
}
}
if (inside && count > 0)
System.out.println("Found: " + count);
}
if you have several methods printing out all the lines may be to much when you are only interested in the number of lines. You can put the names of the methods and the number of lines in a map and print that out.
public static void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
Map<String, Integer> map = new HashMap<>();
while((line = br.readLine())!=null){
lines_inside = 0;
if(line.startsWith("/*St")){
String method = "";
do{
line = br.readLine();
if(line.contains("public")){
method = line.substring(0, ine.indexOf('('));
}
line = line.trim();
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
map.put(method, lines_inside);
}
}
br.close();
for(String s :map.keySet()){
System.out.println(s +" : "+ map.get(s));
}
}
Try to put lines_inside++; in the code like this:
while((line = br.readLine())!=null){
lines_inside++;
...
This gives you the rught number of elements in file.

How to append multiple text in text file

I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.
I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
Make sure the second if condition is satisfied i.e. the line String contains "text2".

Count the amount of times a string appears in a file

I'm trying to figure out how I would read a file, and then count the amount of times a certain string appears.
This is what my file looks like, it's a .txt:
Test
Test
Test
Test
I want the method to then return how many times it is in the file. Any idea's on how I could go about doing this? I mainly need help with the first part. So if I was searching for the string "Test" I would want it to return 4.
Thanks in advanced! Hope I gave enough info!
Add this method to your class, pass your FileInputStream to it, and it should return the number of words in a file. Keep in mind, this is case sensitive.
public int countWord(String word, FileInputStream fis) {
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String readLine = "";
int count = 0;
while((readLine = in.readLine()) != null) {
String words = readLine.split(" ");
for(String s : words) {
if(s.equals(word)) count++;
}
return count;
}
Just wrote that now, and it's untested, so let me know if it works. Also, make sure that you understand what I did if this is a homework question.
Here you are:
public int countStringInFile(String stringToLookFor, String fileName){
int count = 0;
try{
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
int startIndex = strLine.indexOf(stringToLookFor);
while (startIndex != -1) {
count++;
startIndex = base.indexOf(stringToLookFor,
startIndex +stringToLookFor.length());
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return count;
}
Usage: int count = countStringInFile("SomeWordToLookFor", "FileName");
If you have got to the point of reading in each file into a string I would suggest looking at the String method split.
Give it the string code 'Test' and it will return an array of type string - count the number of elements per line. Sum them up to get your total occurrence.
import java.io.*;
public class StringCount {
public static void main(String args[]) throws Exception{
String testString = "Test";
String filePath = "Test.txt";
String strLine;
int numRead=0;
try {
FileInputStream fstream = new FileInputStream(filePath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
strLine = strLine + " ";
String [] strArry = strLine.split(testString);
if (strArry.length > 1) {
numRead = numRead + strArry.length - 1;
}
else {
if (strLine == testString) {
numRead++;
}
}
}
in.close();
System.out.println(testString + " was found " + numRead + " times.");
}catch (Exception e){
}
}
}
I would do this:
open and read the file line by line,
check how oft a line contains the given word...
increase a global counter for that..
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Test.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String word = sc.next();
String line = in.readLine();
int count = 0;
do {
count += (line.length() - line.replace(word, "").length()) / word.length();
line = in.readLine();
} while (line != null);
System.out.print("There are " + count + " occurrences of " + word + " in ");
}

Categories

Resources