I'm able correctly to create and to write into a new file, but don't in a second one or more.
What's wrong?
int numbOfFile = 0;
PrintWriter bw = new PrintWriter("C:path\test" + numbOfFile + ".csv");
for (Map.Entry<String, List<Integer>> entry : inSorting.entrySet()) {
String key = entry.getKey();
numbOfFile++;
if (!(numbOfFile % 3 == 0)) {
bw.println(key + " ");
} else {
bw.close();
new PrintWriter(""C:path\test" + numbOfFile + ".csv"");
bw.println(key + " ");
}
}
bw.close();
Related
I have a method that returns a String and I would like to test if it works correctly. For that I have a test.txt-file that I read and compare to the return value of my method. If I print both Strings out they are exactly the same! Somehow assertEquals still fails.. What am I doing wrong here?
Method to test:
public String statement() {
String result = "Rental Record for " + getName() + "\n";
int frequentRenterPoints = 0;
for (Rental each : this.rentals) {
frequentRenterPoints += each.getFrequentRenterPoints();
// show figures for this rental
result += "\t" + each.getMovie().getTitle() + "\t"
+ " (" + each.getMovie().getQuality() + ")"
+ ": "
+ String.valueOf(each.getCharge()) + "\n";
}
// add footer lines
result += "Amount owed is " + String.valueOf(getTotalCharge()) + "\n";
result += "You earned " + String.valueOf(frequentRenterPoints)
+ " frequent renter points";
return result;
}
Test:
#Test
public void statementReturnsCorrectlyFormattedString() throws IOException {
// given
customer = new Customer("ElonMusk");
Movie movieOne = new Movie("IronMan1", PriceCodes.REGULAR, Quality.HD);
Movie movieTwo = new Movie("AvengersEndGame", PriceCodes.NEW_RELEASE, Quality.FOUR_K);
Rental rentalOne = new Rental();
rentalOne.setMovie(movieOne);
rentalOne.setDaysRented(5);
Rental rentalTwo = new Rental();
rentalTwo.setMovie(movieTwo);
rentalTwo.setDaysRented(1);
List<Rental> rentalList = new LinkedList<Rental>();
rentalList.add(rentalOne);
rentalList.add(rentalTwo);
customer.setRentals(rentalList);
String expectedString = "";
try {
expectedString = readFile("test.txt");
System.out.println("expected: " + "\n" +expectedString);
} catch (IOException e) {
throw new IOException("Error reading statementTestFile!", e);
}
// when
String statement = customer.statement();
// then
System.out.println("statement: " + "\n" + statement);
System.out.println(expectedString.equals(statement));
assertEquals(expectedString, statement);
}
Output: expectedString
expected:
Rental Record for ElonMusk
IronMan1 (HD): 6.5
AvengersEndGame (FOUR_K): 5.0
Amount owed is 11.5
You earned 2 frequent renter points
Output: statement
statement:
Rental Record for ElonMusk
IronMan1 (HD): 6.5
AvengersEndGame (FOUR_K): 5.0
Amount owed is 11.5
You earned 2 frequent renter points
readFile:
private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = "\n";
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
The problem is in the trailing newline you add when reading from a file. You could in trim the string, but what if there were some empty lines at the end of file you wanted to read?
So you can either introduce a 'first line' boolean like that:
boolean isFirstLine = true;
while((line = reader.readLine()) != null) {
if (!isFirstLine) {
stringBuilder.append(ls);
}
stringBuilder.append(line);
isFirstLine = false;
}
Or maybe leave the loop as-is and after it runs delete last character from the builder with:
if (stringBuilder.length() > 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1); // or stringBuilder.lastIndexOf("\n");
}
Or do a substring.
Or maybe read the lines into a List collection like ArrayList and later do String.join("\n", linesCollection);.
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.
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.
Hey im trying to write to a file but im getting an error on the line where it writes the line that goes into each line of a text file, cant figure it out any help would be greatly appreciated
The Writer Code
.
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
writer.close();
i++;
}
The Full Code
import java.io.*;
import java.util.*;
public class StudentMain {
/**
* #param args
*/
//array and sorting variables
public static studentConstructor[] stuArrayOrig = new studentConstructor[23];
private static studentConstructor[] stuArrayIdSort = new studentConstructor[23];
private static studentConstructor[] stuArrayNameSort = new studentConstructor[23];
private static int lineCount = 0;
private static int nElms = 0;
//writer
//studentConstructor variables
public static String fn; //First Name
public static String ln; //Last Name
public static String pn; //Preferred Name
public static int id; //Student Id Number
public static boolean ft;//Full-time Boolean
public static int phn; //Student Phone Number
public static boolean lj;//Loving java Boolean
public static String con;//Continuing
File idSort = new File("stuListSortID.txt");
public static void StuRead()
{
Scanner inFile = null;
try
{
inFile = new Scanner
(new FileReader("Res/students.txt"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
while (inFile.hasNextLine()){
inFile.useDelimiter(",|\\n"); //breaks the lines into single info
ln = inFile.next();
System.out.println(ln);
fn = inFile.next();
System.out.println(fn);
pn = inFile.next();
System.out.println(pn);
id = inFile.nextInt();
System.out.println(id);
ft = inFile.nextBoolean();
System.out.println(ft);
phn = inFile.nextInt();
System.out.println(phn);
lj = inFile.nextBoolean();
System.out.println(lj);
con = inFile.next();
System.out.println(con);
studentConstructor st = new studentConstructor(ln, fn, pn, id, ft, phn, lj, con);
stuArrayOrig[lineCount] = st;
inFile.nextLine();
System.out.println(stuArrayOrig[lineCount]);
lineCount++;
}
//setting info into other arrays
stuArrayIdSort = stuArrayOrig;
stuArrayNameSort = stuArrayOrig;
System.out.println("orig array length" + stuArrayOrig.length);
System.out.println("id array length" + stuArrayIdSort.length);
System.out.println("name array length" + stuArrayNameSort.length);
System.out.println("number of file lines" + lineCount);
inFile.close();
}
public static void stuIdSort()
{
studentConstructor temp;
boolean sorted = false;
while (sorted == false)
{ sorted=true;
for (int i=0; i<stuArrayIdSort.length-1 ; i++)
{
if(stuArrayIdSort[i].getStuId() > stuArrayIdSort[i+1].getStuId())
{
temp = stuArrayIdSort[i+1];
stuArrayIdSort[i+1] = stuArrayIdSort[i];
stuArrayIdSort[i] = temp;
sorted=false;
}
}
}
for(int i=0; i<stuArrayIdSort.length; i++)
{
int getSC = stuArrayIdSort[i].studentId;
System.out.println("number of swaps " + i+1 +" " +getSC);
}
}
//stuArrayIdSort[i].getStuLastName(),stuArrayIdSort[i].getStuFirstName(),stuArrayIdSort[i].getPrefName(),stuArrayIdSort[i].getStuId(),stuArrayIdSort[i].getFTime(),stuArrayIdSort[i].getPhoneNum(),stuArrayIdSort[i].getLovJava(),stuArrayIdSort[i].getCont()
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
writer.close();
i++;
}
}
public static void stuNameSort()
{
}
public static void stuNameWrire()
{
}
}
//lastName, firstName, perName, studentId, fulltime,
Ok, here is what you should do:
What's happening is that you are closing it before it can actually do anything. So, lets move your finally clause to the end of everything:
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
i++;
}
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
I'm not sure you understand how try...catch...finally works. Here's what you have:
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
>>>>>>> **try {writer.close();} catch (Exception ex) {}**
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
//bunch of stuff
writer.write(...);
>>>>>>> **writer.close();**
i++;
}
}
You close writer ONCE before you've even used it (finally block gets executed after the try block), and ONCE inside the loop. So, if somehow the code could make it past the writer.close() in the finally block, it would never make it through the loop more than once.
It is not necessary to close a BufferedWriter. The class makes sure to close it internally.
If you are using Java 7, you might want to consider using the "try-with-resources" syntax, which can simplify a correct implementation of file handling greatly in cases like this. Your original code had some issues, but even the accepted answer has some problems that I believe will result in a NullPointerException in the case where the file can't be opened (unverified).
I think you may also have some problems with your while loop boundary conditions also. I've changed the while loop to the more traditional for loop. Keep in mind that java array elements run from 0 to array.length - 1 inclusive.
public static void stuIDWrite() throws IOException
{
try (FileWriter writer = new FileWriter("Res/stuIDSorted.txt"))
{
for (int i = 0; i < stuArrayIdSort.length; ++i)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn = stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + "," + id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
}
}
}
You could also look at using the "enhanced for loop" syntax for the inner loop that may further streamline things.
With the code below, I am trying to write the key and values of the male and female map to an existing file.
But it shows the following error.
Can somebody help me please.
ERROR# Map.Entry entry = (Map.Entry) entryIter.next();
java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at test.main(test.java:83)
Code
public static void main(String[] args) {
Map<String, List<String>> MaleMap = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> FemaleMap = new LinkedHashMap<String, List<String>>();
try {
Scanner scanner = new Scanner(new FileReader(".txt"));
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
String[] column = nextLine.split(":");
if (column[0].equals("Male") && (column.length == 4)) {
MaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
} else if (column[0].equals("Female") && (column.length == 4)) {
FemaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
}
}
Set<Entry<String, List<String>>> entries = MaleMap.entrySet();
Iterator<Entry<String, List<String>>> entryIter = entries.iterator();
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object maleName = key;
Object maleAge = null;
Object maleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(key + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object maleName = key;
Object maleAge = value1;
Object maleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write(maleAge + "." + maleID + "##;" + "\n"
+ " :class :" + maleName);// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Set<Entry<String, List<String>>> Fentries = FemaleMap.entrySet();
Iterator<Entry<String, List<String>>> FentryIter = Fentries.iterator();
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object Fkey = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = null;
Object femaleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(Fkey + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = value1;
Object femaleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write("map:" + femaleName + " a :Bridge;" + "\n"
+ ":property" + femaleAge + ";" + "\n"
+ ":column" + " " + femaleID + " " + ";");// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Map.Entry entry = (Map.Entry) entryIter.next(); in your second loop is breaking.
After the first while loop that iterates through the males, your iterator has reached the end of the set, and will break when you try to call next().
What you actually want to do is iterate through your females.
Change the line to iterate with your FentryIter:
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) FentryIter.next();
This is most likely the result of copy-paste code, and you need to be careful when doing this. I would recommend re-factoring your code since so much of it is duplicated.