I'm trying to display the information from a text file in a JTextArea I've created in a GUI. I've figured out how to get the info from the file to the JTextArea, but it's only grabbing the last line of the file. I need to display all of the lines. I keep changing the loop around, but can't figure this one out. Any help would be greatly appreciated. Here's a look at my code:
public TextArea() {
initComponents();
try {
FileReader one = new FileReader ("info.txt");
BufferedReader buf = new BufferedReader(one);
String line = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//textArea.setText(line);
while ((line = buf.readLine()) != null) {
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = ("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
textArea.setText(line);
}
//reset token number
tokenNumber = 0;
//textArea.setText(line);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "File not found");
} catch (IOException e){
JOptionPane.showMessageDialog(this, "Data not read");
}
Look at your code:
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = ("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
textArea.setText(line);
}
Everytime you find a new token you set the textarea val to last token found.
So obviously text area will display only last line.
You can try something like:
textArea.setText(textArea.getText() + line);
I think You are overriding the line variable.
line+=...
Concatenate, and then set the value of the whole line concatenated outside the loop.
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = line +"\n"+("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
}
textArea.setText(line);
Related
I'm trying to get the print output and store it into an array of Strings in order to write the values in a CSV File. The problem that comes up is that when a run the code, from 100 lines printed, only the last line gets stored:
public void organize(String line) throws IOException {
CSVWriter writer = new CSVWriter(new FileWriter("out.csv"), '\t');
String[] token = line.split(",");
String[] DependencyItems = token[1].split(" ");
List<String> entriesList;
String[] entries;
String row = "";
for (int i = 0; i < DependencyItems.length; i++) {
row = token[0] + "," + DependencyItems[i] + "," + token[2] + "," + token[3] + "," + token[5]+ "," + token[6]
+ "," + token[7]+ "," + token[8]+ "," + token[9] + "," + token[10] + "," + token[11] + "," + token[12]
+ "," + token[13] + "," + token[14] + "," + token[15] + "," + token[16]+ "," + token[17]
+ "," + token[18]+ "," + token[19]+ "," + token[20]+ "," + token[21] + "," + token[22]
+ "," + token[23]+ "," + token[24]+ "," + token[25]+ "," + token[26]+ "," + token[27]
+ "," + token[28]+ "," + token[29];
}
System.out.println(row);
entriesList = Arrays.asList(row);
entries = entriesList.toArray(new String[0]);
writer.writeNext(entries);
writer.close();
}
What I am doing wrong?
row = <big long string>
You are always resetting row then all of the stuff after the loop is just using the last value of row. If you want to use all the values, perhaps the code after the loop should be in the loop? At the very least it looks like these 2 lines belong in the loop.
System.out.println(row);
entriesList = Arrays.asList(row);
Note that if the scope of row was limited to just be inside the loop, then this may help to identify this type of issue as it would not be valid outside the loop.
I'm pretty new to Java and I'm having some trouble figuring out where I'm going wrong with my program. I have it so it's doing a mad libs sort of thing where it reads a document with questions(or categories), then prompts for an answer on loop till it has all the answers. It commits these answers to a text file called "answers" then reads the file and prints a message, along with another file containing the full madlib.
I don't actually get an error upon compiling but after I've input all the answers I get
Exception in thread "main" java.util.NoSuchElementException: no line found
-at java.util.Scanner.nextLine(Scanner.java:1540)
-at reader.main(reader.java:68)
Here's the complete code for reference
import java.util.Scanner; // importing scanner object for usage
import java.io.*;
import java.io.PrintWriter;
public class reader{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("enter the name of a file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
int limit = inputFile.nextInt();
int n;
inputFile.nextLine();
PrintWriter answers = new PrintWriter("answers.txt");
for(n = 0; n < limit; n++)
{
String line = inputFile.nextLine();
System.out.println(line);
String answer = keyboard.nextLine();
answers.println(answer);
}
inputFile.close();
answers.close();
File useanswers = new File("answers.txt");
Scanner inputFile2 = new Scanner(useanswers);
String outputline = inputFile2.nextLine();
String outputline2 = inputFile2.nextLine();
String outputline3 = inputFile2.nextLine();
String outputline4 = inputFile2.nextLine();
String outputline5 = inputFile2.nextLine();
String outputline6 = inputFile2.nextLine();
String outputline7 = inputFile2.nextLine();
String outputline8 = inputFile2.nextLine();
String outputline9 = inputFile2.nextLine();
String outputline10 = inputFile2.nextLine();
String outputline11 = inputFile2.nextLine();
String outputline12 = inputFile2.nextLine();
String outputline13 = inputFile2.nextLine();
String outputline14 = inputFile2.nextLine();
String outputline15 = inputFile2.nextLine();
String outputline16 = inputFile2.nextLine();
String outputline17 = inputFile2.nextLine();
String outputline18 = inputFile2.nextLine();
String outputline19 = inputFile2.nextLine();
PrintWriter result = new PrintWriter("Madlibs_result.txt");
System.out.println("Batman is " + outputline + ". Teenager " + outputline2 +
"was traumatized by " + outputline3 + "his parent's murder and vowed to " + outputline4 +
" their deaths by bringing the " + outputline5 + " to justice. " + outputline6 + " used his " +
outputline7 + "fortune to study criminology, to train his body to " + outputline8 + " perfection, " +
"and to acquire hight tech vehicles and " + outputline9 + " to fight crime in his homw town of " + outputline10 + ". One night " +
outputline11 + "was " + outputline + " by a bat outside his window and decided to dress himself as a \"bat man\" to strike " +
outputline12 + " in the \"" + outputline13 + " and " + outputline14 + "\" hearts of " + outputline15 + ". From that moment forward, " +
outputline16 + " became \"Batman\" in his altered " + outputline17);
result.println("Batman is " + outputline + ". Teenager " + outputline2 +
"was traumatized by " + outputline3 + "his parent's murder and vowed to " + outputline4 +
" their deaths by bringing the " + outputline5 + " to justice. " + outputline6 + " used his " +
outputline7 + "fortune to study criminology, to train his body to " + outputline8 + " perfection, " +
"and to acquire hight tech vehicles and " + outputline9 + " to fight crime in his homw town of " + outputline10 + ". One night " +
outputline11 + "was " + outputline + " by a bat outside his window and decided to dress himself as a \"bat man\" to strike " +
outputline12 + " in the \"" + outputline13 + " and " + outputline14 + "\" hearts of " + outputline15 + ". From that moment forward, " +
outputline16 + " became \"Batman\" in his altered " + outputline17);
result.close();
}
}
Resolved, I had too many String outputline... lines, and I assume when it tried to go to the nonexistent 19th and 20th lines of the text file created, it gave me an error.
We have a problem with writing our ArrayList to a file.
The file remains empty. We don't find any mistake in our code.
please help us, our deadline is within a few hours...
public void rapportAssortiment(String winkelNaam) throws Exception
{
ArrayList <Artikel> assortiment = db.rapportAssortiment(winkelNaam);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new FileOutputStream("RapportAssortiment.txt",true));
outputStream.println("Rapport van het assortiment van winkel " + winkelNaam);
outputStream.println("Artikelnummer" + ";" + "Artikelnaam" + ";" + "Prijs" + ";" + "Aantal bonuspunten" + ";" + "Aantal bonuspunten nodig" + ";" + "Minimum aantal stuks" + ";" + "Minimum bedrag" + ";" );
for(int i = 0; i< assortiment.size(); i++)
{
outputStream.println(assortiment.get(i).getArtikelNr() + ";" + assortiment.get(i).getArtikelNaam() + ";" + assortiment.get(i).getPrijs() + ";" + assortiment.get(i).getAantPunten() + ";" + assortiment.get(i).getAantPuntenNodig() + ";" + assortiment.get(i).getMinAantStuks() + ";" + assortiment.get(i).getMinBedrag() );
}
}
catch(Exception exc)
{
System.out.println("Rapport trekken mislukt.");
}
}
After you're done with writing
outputStream.flush();
outputStream.close();
I am taking one csv comparing each line with every line of another csv to find matches.
I then need to add some elements from the second csv with some from the first and write it to a new file.
It works for the first lines of the csv then gets the ArrayIndexOutOfBoundsException.
I understand how arrays work and I've checked my csv and as far as I can see I'm not going out of bounds.
The first csv has 8 fields and contains all the customer info. The second has 15 fields and holds sales info on customers. the first 2 fields [0] and [1] are the same in both csv's if there is a record of sales.
If anyone could have a quick look I may be missing something stupid.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at excel.parse.ExcelParse.main(ExcelParse.java:61)
package excel.parse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
public class ExcelParse {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String csvFile2 = "\\\\SBS2011\\RedirectedFolders\\Josh.Hickinbotham\\My Documents\\Customer_Sales_Trends_Summary_by_Sales_Order_114641390.csv";
String csvFile1 = "\\\\SBS2011\\RedirectedFolders\\Josh.Hickinbotham\\My Documents\\All_Customers_Listing_for_Rep_114337469.csv";
BufferedReader br = null;
BufferedReader br2 = null;
BufferedWriter bw = null;
String line = "";
String line2 = "";
String csvSplitBy = ",";
Boolean match = false;
try {
br = new BufferedReader(new FileReader(csvFile1));
bw = new BufferedWriter(new FileWriter("\\\\SBS2011\\RedirectedFolders\\Josh.Hickinbotham\\My Documents\\newcsv.txt"));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] customer = line.split(csvSplitBy);
System.out.println(customer[1]);
br2 = new BufferedReader(new FileReader(csvFile2));
while ((line2 = br2.readLine()) != null) {
String[] file2 = line2.split(csvSplitBy);
if (customer[1].equals(file2[1])) {
match = true;
bw.write(customer[0] + "," + customer[1] + "," + customer[2] + "," + customer[3] + "," + customer[4] + ","
+ customer[5] + "," + customer[6] + "," + customer[7] + ","+ file2[2] +","+ file2[3] + "," + file2[4] + "," + file2[5] + ","
+ file2[6] + "," + file2[7] + "," + file2[8] + "," + file2[9] + "," + file2[10] + "," + file2[11] + "," + file2[12] + ","
+ file2[13] + "," + file2[14]+"\r\n");
System.out.println(":::MATCH " +customer[1]+" : "+file2[1]+" :::");
} else {
match = false;
}
}
if (match == false) {
bw.write(customer[0] + "," + customer[1] + "," + customer[2] + "," + customer[3] + "," + customer[4] + ","
+ customer[5] + "," + customer[6] + "," + customer[7] + "," + "," + "," + "," + "," + "," + "," + "," + "," + "," + ","
+ "," + ","+"\r\n");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br2 != null) {
try {
br2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
Try displaying what customer is before it goes into the if match == false.
May help to see what exactly you are dealing with. :)
What about a simple check on the bounds of the result of "split" ? if you dump your line at the point where the bounds are not OK, you will see the faulty input data....
I think the problem is in your file containing the csv. Maybe debug it and stop at the line where you get the exception to check what data customer contains.
But what I wanted to note:
I'm not sure your program is doing what it is supposed to do. When it finds a match it will print it out, but then keep going in the inner while loop and so at the end match will be false again and you print out the non-match.
So I think you want to put a break:
if (customer[1].equals(file2[1])) {
match = true;
bw.write(customer[0] + "," + customer[1] + "," + customer[2] + "," + customer[3] + "," + customer[4] + ","
+ customer[5] + "," + customer[6] + "," + customer[7] + ","+ file2[2] +","+ file2[3] + "," + file2[4] + "," + file2[5] + ","
+ file2[6] + "," + file2[7] + "," + file2[8] + "," + file2[9] + "," + file2[10] + "," + file2[11] + "," + file2[12] + ","
+ file2[13] + "," + file2[14]+"\r\n");
break;
}
I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...