I'm trying to find an object in a list from a text file
Example:
L;10;€10,50;83259875;YellowPaint
-H;U;30;€12,00;98123742;Hammer
G;U;80;€15,00;87589302;Seeds
By inserting 98123742 by input with scanner, i want to find that string.
I tried to do this:
private static void inputCode() throws IOException {
String code;
String line = null;
boolean retVal = false;
System.out.println("\ninsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if (token[0].equals(code) && token[1].equals(code)) {
retVal = true;
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("impossible open the file " + fileName);
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
System.out.println(retVal);
}
How can i print "-H;U;30;€12,00;98123742;Hammer" inserting "98123742" (that is the code of the product) ?
Why are you splitting in the first place? For such a simple usecase, and with that line format, I'd go with
line.contains(";" + code);
Not much else to do.
This program is meant to see two files located in a particular folder and then merge those two files and create a third file which is does. From the third merged file it is then searching for a keyword such as "test", once it finds that key word it prints out the location and the line of the keyword which is what is somewhat doing. What is happening is when I run the program it stops after the finds the keyword the first time in a line but it will not continue to search that line. So if there is multiple keyword 'test' in the line it will only find the first one and spit back the position and line. I want it to print both or multiple keywords. I think it is because of the IndexOf logic which is causing the issue.
import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Concatenate {
public static void main(String[] args) {
String sourceFile1Path = "C:/Users/me/Desktop/test1.txt";
String sourceFile2Path = "C:/Users/me/Desktop/test2.txt";
String mergedFilePath = "C:/Users/me/Desktop/merged.txt";
File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);
File mergedFile = new File(mergedFilePath);
mergeFiles(files, mergedFile);
stringSearch(args);
}
private static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stringSearch(String args[]) {
try {
String stringSearch = "test";
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/me/Desktop/merged.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file");
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
}
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
It's because you are searching for the word once per line in your while loop. Each iteration of the loop takes you to the next line of the file because you are calling bf.readLine(). Try something like the following. You may have to tweak it but this should get you close.
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
while(indexfound > -1)
{
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
indexfound = line.indexOf(stringSearch, indexfound);
}
}
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");
}
I was using my code to do a replace line feature. It was working initially but suddenly my new file became blank and the code did not bring me back to the AdminMenu(), as well as the file not being renamed. There is also another issue where if I use "\r\n" there will be a blank line on top of my file which I am trying to remove. I tried using \n after totalChips, but it doesn't seem to work. I could use some advice on this.
output
<Blank File>
expected output
Line1|password|500
Line2|password|600
//ModifiedLine can be either line based on UserName
codes are below
public static void AddChips() {
File oldFileName = new File("players.dat");
File tmpFileName = new File("newplayers.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN))
line = Username + "|" + Password + "|" + totalChips;
bw.write("\r\n"+line);
}
bw.close();
br.close();
oldFileName.delete();
tmpFileName.renameTo(oldFileName);
AdminMenu();
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
new Error
java.lang.ArrayIndexOutOfBoundsException: 1
at testcode.AddChips(testcode.java:53)
at testcode.main(testcode.java:11)
So I've been working on a program that will display the line number and the line itself of the searched text string. If I search dog, and I have lines in my text file that contain the word dog, those lines and line numbers should be shown. I also have created a method that counts the characters, words, and lines of a text file. However, the problem I am having is that whenever I run my program I don't get the line numbers with the lines of the searched text. I successfully get the text from the text file in the console and I successfully get the number of lines, words, etc.
Here's my written code, I am guessing it has to do something with the fact that I don't have a "return results;" statement, but I am not sure where to put it, and if I add it to the end of "+ characters + " characters. "" line by doing "+ results", it just gives me empty brackets.
Maybe I am doing something wrong? Perhaps something to do with closing the file and stream, not sure. Please help, I've tried moving stuff around but no luck.
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
Here's the main class if needed:
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
public class BasicFile {
File file1;
JFileChooser selection;
File file2 = new File(".", "Backup File");
public BasicFile() {
selection = new JFileChooser(".");
}
public void selectFile() {
int status = selection.showOpenDialog(null);
try {
if (status != JFileChooser.APPROVE_OPTION) {
throw new IOException();
}
file1 = selection.getSelectedFile();
if (!file1.exists()) {
throw new FileNotFoundException();
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File Not Found ", "Error", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.exit(0);
}
}
public void backupFile() throws FileNotFoundException {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(new FileInputStream(file1));
out = new DataOutputStream(new FileOutputStream(file2));
try {
while (true) {
byte data = in.readByte();
out.writeByte(data);
}
} catch (EOFException e) {
JOptionPane.showMessageDialog(null, "File has been backed up!",
"Backup Complete!", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found ",
"Error", JOptionPane.INFORMATION_MESSAGE);
}
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
display(e.toString(), "Error");
}
}
}
boolean exists() {
return file1.exists();
}
public String toString() {
return file1.getName() + "\n" + file1.getAbsolutePath() + "\n" + file1.length() + " bytes";
}
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
void display(String msg, String s) {
JOptionPane.showMessageDialog(null, msg, s, JOptionPane.ERROR_MESSAGE);
}
}
You are nearly there.
reinitialize your FileReader and LineNumberReader before your while ((line = lnr.readLine()) != null) loop.
Then your ArrayList will be full of the #String that I think you desire.
what you can do is start counting the lines in the file (starting by 0), then increase by 1 every time a new line is found.. then check if the string you want to find is contained in the line, then print the number of the line where the keyword is found (using the contains() function in Java). I assumed you want to check for both upper and lower case, if you don't want that then simply remove the toLowerCase() ! So, read the file properly in Java:
long lineNumber = 0;
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String line = myReader.readLine();
while(line != null){
lineNumber++;
System.out.println("The line I am now examining is : " + line + " and the line number is : " + lineNumber);
if line.toLowerCase().contains(word.toLowerCase()) {
System.out.println("Line number: " + lineNumber + " contains keyword : " + word);
line = myReader.readLine();
}