while loop needs to continue - java

I have this code
static String sCurrentLine = null;
/* keyword */
static String keyword = null;
Scanner keywordFile = null, siteFile = null;
try {
keywordFile = new Scanner(new File("/home/mearts/keywords.txt"));
siteFile = new Scanner(new FileReader(fileChooser.getSelectedFile()));
sCurrentLine = siteFile.nextLine().trim();
keyword = keywordFile.nextLine().trim();
while (sCurrentLine != null){
while (keywordFile.hasNext() || keyword == null) {
System.out.println("Line--> " + keyword);
System.out.println("Current here >>" + sCurrentLine);
if (sCurrentLine.contains(keyword)) {
System.out.println("Found it-->> " + keyword);
keyword = keywordFile.nextLine();
System.out.println("next keyword " + keyword);
///* reset search to top of site file */
siteFile = new Scanner(new
FileReader(fileChooser.getSelectedFile()));
sCurrentLine = siteFile.nextLine().trim();
}
else {
sCurrentLine = siteFile.nextLine();
if (sCurrentLine == null) {
break;
}
if (!sCurrentLine.matches(keyword)){
System.out.println("The following keyword " + keyword + " does not exist in file "
+ fileChooser.getSelectedFile());
}
}
} //2nd while loop
}
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
siteFile.close();
keywordFile.close();
}
and i have a text file called keywords which has a list of keywords in it,
but my logic is off an I cannot figure out why.
I think I may need to run the loop one last time but not sure how to do that
My issue is that the last word in the keyword file never gets read in. so the program stops at the 2nd to last element in the text file.

I am not sure that I understand what your code should do.
If I understood correctly your code, your task is to read keywords from a file with keywords and then find all keywords in another file. Is it correct?
You should separate reading keywords from the file and search for them in the file. You should 'load' keywords in a list and then search through the file.
To load keywords in list
keywordFile = new Scanner(new File("/home/mearts/keywords.txt"));
List<String> keywordsList = new ArrayList<>();
while (keywordFile.hasNextLine()) {
keywordsList.add(keywordFile.nextLine());
}
And to search for keywords in the file
siteFile = new Scanner((Readable) new FileReader(fileChooser.getSelectedFile()));
while (siteFile.hasNextLine()) {
String sCurrentLine = siteFile.nextLine().trim();
for (String keyword : keywordsList) {
if (sCurrentLine.contains(keyword)) {
System.out.println("Found it-->> " + keyword);
break;
}
}
System.out.println(
"The following keyword " + keyword + " does not exist in file " + fileChooser.getSelectedFile());
}
I hope this will help :)

Related

Read specific row in csv

Is there any way through which we can read specific row record on the basis of value. For example my csv file is:
ProductID,ProductName,price,availability,type
12345,Anaox,300,yes,medicine
23456,Chekmeter,400,yes,testing
I want to get the row whose ProductID is ‘23456’. i was checking the new CsvReader(“D:\products.csv”).getRawRecord() method, but it doesn’t have any method parameters.
Iterator iterator = CsvReader("D:\\products.csv").Iterator();
while(iterator.hasNext()){
if((String[] string = (iterator.next))[0] == 23456)
sout("Found the row: " + string[0] + ", " + string[1] + ", " + string[2] + ", " + string[3] + ", " + string[4]);
}
And regarding your concern about performance:
with 1.000 elements this will still be way faster than you need it to be, worry when you get to 1.000.000 elements
If you want the reading of the Csv to be performant you gotta use a performant way of storing your IDs. If you are just incrementing your IDs everytime a new one is made and never delete an ID you can use the ID as an index to directly get the correct line.
public static ArrayList<String> getSpecificRowData(String s) throws IOException
{
String csvFile = s;
BufferedReader br = null;
String line = "";
ArrayList<String> arr=new ArrayList<>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
//write your row name in the given csv file
if(line.contains("write your row name"))
{
arr.add(line);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return arr;
}
//return the row in the form of ArrayList
ArrayList<String> li=getSpecificRowData("FileName12.csv");
System.out.println(li);

Request parameters coming from jsps are changed when two different users access the code same time

public String generateDataPDF() {
System.out.println("Inside generate PDF");
String filePath = "";
HttpSession sess = ServletActionContext.getRequest().getSession();
try {
sess.setAttribute("msg", "");
if (getCrnListType().equalsIgnoreCase("F")) {
try {
filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
System.out.println("File stored path : " + filePath);
target = new File(filePath);
FileUtils.copyFile(crnFile, target);
} catch (Exception e) {
System.out.println("File path Exception " + e);
}
}
System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
+ " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());
String srtVAL = "";
String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
getOutputPath(), getGenMode(), getRenType()};
//INS DB Connection
con = getInsjdbcConnection();
ArrayList selectedCRNList = new ArrayList();
String selectedCRNStr = "";
selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);
String[] fileRes = selectedCRNStr.split("\\,");
if (fileRes[0].equalsIgnoreCase("FAIL")) {
System.out.println("fileRes is FAIL beacause of other extension file.");
sess.setAttribute("pr", "Please upload xls or csv file.");
return SUCCESS;
}
System.out.println("List file is : " + selectedCRNStr);
String st[] = srtVAL.split("[*]");
String billDateStr = DateUtil.getStrDateProc(new Date());
Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
String minAMPM = DateUtil.getTimeDate(new Date());
String str = "";
String batchID = callSequence();
try {
System.out.println("Inside Multiple policy Generation.");
String userName=sess.getAttribute("loginName").toString();
String list = getProcessesdList(userName);
if (list != null) {
System.out.println("list is not null Users previous data is processing.....");
//setTotalPDFgNERATEDmSG("Data is processing please wait.");
sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
return SUCCESS;
}
String[] policyNo = selectedCRNStr.split("\\,");
int l = 0, f = 0,counter=1;
for (int j = 0; j < policyNo.length; j++,counter++) {
String pdfFileName = "";
int uniqueId=counter;
globUniqueId=uniqueId;
insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);
System.out.println("Executing Proc one by one.");
System.out.println("policyNo[j]" + policyNo[j]);
System.out.println("getOptionId()" + getOptionId());
System.out.println("seqValue i.e batchId : " + batchID);
}
str = callProcedure(policyNo[j], getOptionId(), batchID);
String[] procResponse = str.split("\\|");
for (int i = 0; i < procResponse.length; i++) {
System.out.println("Response is : " + procResponse[i]);
}
if (procResponse[0].equals("SUCCESS")) {
Generator gen = new Generator();
if (getPdfName().equalsIgnoreCase("true")) {
System.out.println("Checkbox is click i.e true");
pdfFileName = procResponse[1];
} else {
System.out.println("Checkbox is not click i.e false");
String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
if (getLogoType().equals("0") || getLogoType().equals("2")) {
System.out.println("If logo is O or 1");
pdfFileName = fileName[1];
} else if (getLogoType().equals("1")) {
System.out.println("If logo is 2");
pdfFileName = fileName[0];
}
}
b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
l++;
updateData(uniqueId,batchID, "Y");
} else {
f++;
updateData(uniqueId,batchID, "F");
}
}
sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
}catch (Exception e) {
updateData(globUniqueId,batchID, "F");
System.out.println("Exception in procedure call");
setTotalPDFgNERATEDmSG("Fail");
e.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
}catch (Exception ex) {
ex.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
System.out.println("Above second return");
return SUCCESS;
}
GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?
As per your comment, this is what I would do, It's probably not the best way to do !
Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.
Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)
"Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.
NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.
Thus, your code should be refactored a little bit.

Error. BufferedWriter repeating lines at end of file

I have here an error and dont know what is happening.
My class gets a vector of hashmaps and a rute, and then write that hashmap to a file in that route.
This is the code:
/* Variables de entrada */
Vector vecHm = (Vector) context.getAttribute(sVecHashmap);
String strFileLocation = "" + context.getAttribute(sFileLocation);
// Inicializamos variables
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
try
{
fileWriter = new FileWriter(strFileLocation,true);
bufferedWriter = new BufferedWriter(fileWriter);
String linea = "";
String lineaCabecera = "";
for (int i=0;i<vecHm.size();i++)
{
HashMap hm = (LinkedHashMap) vecHm.get(i);
Iterator it = hm.entrySet().iterator();
linea = "";
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
if (i==0)
{
if (lineaCabecera.equals("") == false)
{
lineaCabecera = lineaCabecera + ";";
}
lineaCabecera = lineaCabecera + (String)pairs.getKey();
}
if (linea.equals("") == false)
{
linea = linea + ";";
}
linea = linea + (String)pairs.getValue();
//it.remove(); // avoids a ConcurrentModificationException
}
System.out.println("PRF:: HashmapToFile:: Iteracion: " + i + ". Linea: " + linea);
if (i==0)
{
System.out.println("PRF:: Pinto Cabecera. ");
bufferedWriter.write(lineaCabecera);
bufferedWriter.newLine();
//bufferedWriter.write('\n');
}
bufferedWriter.write(linea);
bufferedWriter.newLine();
//bufferedWriter.write('\n');
}
} catch (Exception e)
{
e.printStackTrace();
throw new WFException(" ERROR writing the file");
} finally
{
try
{
// Cerramos el fichero
bufferedWriter.close();
fileWriter.close();
} catch (Exception e)
{
e.printStackTrace();
throw new WFException(" ERROR closing the file");
}
}
I have a trace that show me the line to write in the file:
System.out.println("PRF:: HashmapToFile:: Iteracion: " + i + ". Linea: " + linea);
The log that i see is this (i will put only the last four iterations):
PRF:: HashmapToFile:: Iteracion: 90. Linea: eufekeptuil;null;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo
PRF:: HashmapToFile:: Iteracion: 91. Linea: hwukbzakmfuutrhnfzm;null;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo
PRF:: HashmapToFile:: Iteracion: 92. Linea: Securitas Europe;29-JAN-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo
PRF:: HashmapToFile:: Iteracion: 93. Linea: Tarifa New 544;05-FEB-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo
But... when i see the file... i have this at the end:
Securitas Europe;29-JAN-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo -OK. Perfect-
Tarifa New 544;05-FEB-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo -OK. Perfect-
And then:
N-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo (repeated and unfinished line)
Tarifa New 60;15-JAN-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo (repeated line)
vjvrqgxavk;null;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo (repeated line)
And another 15 more lines repeated.
Any clue?
Thanks all
Forget the problem. The files are good. The problem is in the downloader. The system is putting more data in that functionality.

Reading from a file with empty line

I am currently working on a program for one of my java class and I keep running into a wall with file reading! I am using a JTable to display the information so when the information is read from a file it is added to a row. Whenever there is a blank row the scanner cannot read it and throw an error! i get a java.util.NoSuchElementException on the last scanning line! As of right no i am suing two separate scanners. I had attempted to use the String.split method that that also gave me an error (ArrayIndexOutOfBoundsException: 0). I will post the reading a saving methods below (both two scanner version and split).
private void read() {
try {
Scanner scanner = new Scanner(new File("games.dat"));
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNext()) {
String[] tableRow = new String[6];
Scanner recIn = new Scanner(record);
recIn.useDelimiter("\\s*\\|\\s*");
tableRow[0] = recIn.next();
tableRow[1] = recIn.next();
tableRow[2] = recIn.next();
tableRow[3] = recIn.next();
tableRow[4] = recIn.next();
//recIn.next();
recIn.close();
model.addRow(new Object[]{tableRow[0],
tableRow[1], tableRow[2],
tableRow[3], tableRow[4]});
}scanner.close();
scanner = null;
} catch (Exception ex) {
JOptionPane.showConfirmDialog(null, "Could not connect to file! Make sure you are not in zipped file!",
"Warning!", JOptionPane.OK_OPTION,
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
private void save() {
for (int i = 0; i < model.getRowCount(); i++) {
String data = model.getValueAt(i, 0) + "|" + model.getValueAt(i, 1)
+ "|" + model.getValueAt(i, 2) + "|" + model.getValueAt(i, 3)
+ "|" + model.getValueAt(i, 4) + "|";
games.add(data);
}
try {
for (int i = 0; i < games.size(); i++) {
fileOut.println(games.get(i));
}
fileOut.close();
} catch (Exception ex) {
JOptionPane.showConfirmDialog(null, "Could not connect to file! Make sure you are not in zipped file!",
"Warning!", JOptionPane.OK_OPTION,
JOptionPane.ERROR_MESSAGE);
}
}
recIn.next(); will fail if the line is empty, guard it with hasNext():
Scanner recIn = new Scanner(record);
recIn.useDelimiter("\\s*\\|\\s*");
if (recIn.hasNext()) {
tableRow[0] = recIn.next();
tableRow[1] = recIn.next();
tableRow[2] = recIn.next();
tableRow[3] = recIn.next();
tableRow[4] = recIn.next();
}
This assumes that when there is one element on the record, all of them are there. If this cannot be guaranteed, you need to protect each next() call with hasNext() and decide what to do when you run out of elements in the middle of a record.
Also, you seem to have an infinite loop:
while (scanner.hasNext()) {
// no calls to scanner.next()
}
Did you leave out String record = scanner.next(); from the top of that loop?
From the java.util.Scanner JavaDoc, there is this method, skip():
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#skip%28java.util.regex.Pattern%29
The last line reads, "Note that it is possible to skip something without risking a NoSuchElementException by using a pattern that can match nothing, e.g., sc.skip("[ \t]*")."
So, perhaps add as the first call of your loop, scanner.skip("[ \t]*);

java.util.ConcurrentModificationException Exception error

i am trying to make a java application with GUI.
i am writing a code that i want to let the User change some data and save these changes on a text file. Before doing that i want to delete the old data that is changed from a list and then rewrite the new data with the last change.if i am missing any class you wanted to see please tell me i will put it online as fast as possible
this is my
public void saveChanges(footBall Player, String name, String level,
int[] scores, int footSize) {
try {
if (CompetitorsList.size() != 0) {
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
String Number = Player.playerNumber + "";
if (C.getPlayerNumberAsString().equals(Number)) {
System.out.println("c");
//the error hit me here when i try to remove the object from the list the exception error is java.util.ConcurrentModificationException
CompetitorsList.remove(C);
}
}
}
Name NewName = new Name(name);
System.out.println("Please get in2");
footBall NewPlayer = new footBall(Player.playerNumber, scores,
level, footSize, NewName);
CompetitorsList.add(NewPlayer);
SaveOnFile();
} else {
System.out.println("No List");
}
} catch (Exception ex) {
System.out.print("testing4");
System.out.print("something wrong" + ex);
}
}
this is the SaveOnFile method:
public void SaveOnFile() {
String scoresInString;
FileWriter fw;
try {
fw = new FileWriter("footBall");
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
footBall Scores = new footBall();
scoresInString = Scores.returnScoreAsString(C.scores);
fw.write(C.playerNumber + ", " + C.name.getFullName()
+ ", " + C.level + ", " + scoresInString + ","
+ ((footBall) C).footSize() + "\n");
fw.write("\r\n");
}
}
fw.close();
}
// message and stop if file not found
catch (FileNotFoundException fnf) {
System.out.println("File not found ");
System.exit(0);
}
// stack trace here because we don't expect to come here
catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}
}
Calling remove() on a collection invalidates all active iterator. Instead, you have to use the Iterator.remove() method:
for(Iterator<Competitors> it = CompetitorsList.iterator(); it.hasNext(); ) {
Competitors C = it.next();
if(C instanceof ...) {
if(C.getPlayerNumberAsString().equals(Number))
it.remove();
...
This way, the iterator() knows about how the collection changes, which otherwise wouldn't be possible since the ArrayList doesn't track the Iterators it generated.
Alternatively, if you want to use the same "for-next" syntax and not change to the Iterator syntax, collect all the objects to be removed into a temporary collection. e.g.
ArrayList<Competitors> removeThese = new ArrayList<Competitors>();
for (Competitors C : CompetitorsList) {
if (wantToRemove(C)) // your number logic goes here...
removeThese.add(C);
}
CompetitorsList.removeAll(removeThese);

Categories

Resources