How to write a list to CSV with Super CSV - java
Exception in thread "main" org.supercsv.exception.SuperCsvException: The number of columns to be processed (229326) must match the number of CellProcessors (8):
I believe i may have to redo what im doing using supercsv as it may be easier in the long run however im open to any other suggestions. I simply want to write back to a csv file, i have a list with all the data in it however the ouput is like this
4350 02/06/2013 3965.21 0.0 0.0 0.0 0.0 0.0,
4698 02/06/2013 498.16 0.0 0.0 0.0 0.0 0.0,
4992 02/06/2013 97.87 87.82 6.05 0.0 0.0 0.0,
4441 02/06/2013 18.8 71.98 11.6 0.0 0.0 -42.5, 54092 02/06/2013 105.11 118.82 6.24 0.0 0.0 0.0,
I've managed to get the out put i want by replacing strings within the list however when it runs it hangs and i believe its due to how i'm writing back to the csv, i'm not sure, what else to do other than to write it back to the csv diffrently not using super csv. The error i get is
"1805","31/07/2013","-233.4","0.0","0.0","0.0","0.0","0.0"
"8054","31/07/2013","280.45","82.38","52.38","0.0","0.0","-200.0"The number of columns to be processed (1) must match the number of CellProcessors (8):
My witer class is as follows
package writer;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.supercsv.cellprocessor.FmtDate;
import org.supercsv.cellprocessor.ParseDouble;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvListWriter;
import org.supercsv.io.ICsvListWriter;
import org.supercsv.prefs.CsvPreference;
public class RentStatementsWriter {
public ArrayList rData;
private List<String> csvData;
char b = ',';
public RentStatementsWriter(ArrayList rentData) {
rData = rentData;
ICsvListWriter listWriter = null;
try{
listWriter = new CsvListWriter(new FileWriter("rentl.csv"),CsvPreference.STANDARD_PREFERENCE);
CellProcessor[] processors =new CellProcessor[]{
new ParseInt(),
new FmtDate("dd/MM/yyyy"),//
new ParseDouble(),
new ParseDouble(),
new ParseDouble(),
new ParseDouble(),
new ParseDouble(),
new ParseDouble(),
};
final String [] header = new String []{"_num", "End_Date", "bal_val","rval","cval","bf_val","aval","pval"};
System.out.print("to string "+rData.toString().replaceFirst(" ", "\"").replaceAll("\\,"," \\,").replaceAll(" ", "").replaceAll(" ", "\"\\,\"").replaceAll("\"\\,\"\\,", "\"\n\""));
csvData = Arrays.asList(rData.toString().replaceFirst(" ", "\"").replaceAll("\\,"," \\,").replaceAll(" ", "").replaceAll(" ", "\"\\,\"").replaceAll("\"\\,\"\\,", "\"\""));
/*
* replace
* .replaceAll(" ", "\"\\,\"")
*/
listWriter.writeHeader(header);
listWriter.write(csvData, processors);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print(e+" file unable to write");
} finally {
if(listWriter !=null){
try {
listWriter.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("list writer");
}
}
}
}
String listToCsv(List<String> listOfStrings, char separator) {
StringBuilder sb = new StringBuilder();
// all but last
for(int i = 0; i < listOfStrings.size() - 1 ; i++) {
sb.append("\""+listOfStrings.get(i)+"\"");
sb.append(separator);
}
// last string, no separator
sb.append(listOfStrings.get(listOfStrings.size()-1));
return sb.toString();
}
}
What am i missing in this syntax, or is there a better way of doing this task
There's a couple of problems:
ParseInt and ParseDouble are used for reading CSV Strings into Integer and Double respectively. See the handy table here to see what cell processors can be used for reading/writing or both. You can leave them null if you want, and Super CSV will just call toString() on each object.
The exception you're getting (1 column / 8 processors) indicates that you're expecting there to be 8 columns (i.e. 8 elements in your List), but there's only 1. You're only passing a single String into Arrays.asList() - looks like you're assuming this method actually splits the String into a List (it doesn't!).
Why are you converting your rent data List to a String? That is really bizarre. If your data needs any manipulation (I'm not sure if it does), then you should be updating each element in your List, not converting the whole List to a String then trying to split it up again.
What is the output when you don't do any replacement, i.e. what happens when you pass your rentData list directly to listWriter.write()?
Can I suggest you fix the processor set up (replace the ParseInt and ParseDouble with null), pass the rentData List directly to Super CSV...
listWriter.write(rentData, processors);
...then post the result (output/stacktrace) to your question.
The Solution to this question lies in the question.
The number of columns to be processed (1) must match the number of
CellProcessors (8):
You are actually having more number of comma separated data in a row than you initially told SuperCSV.
final String [] header = new String []{"_num", "End_Date", "bal_val","rval","cval","bf_val","aval","pval"};
This puts SuperCSV to assume that only 8 number of values expected for each row and each column corresponds to one header. If you pass more values in row, it doesn't know what's that value corresponds to, so it's throwing Exception.
This link gives you how to define optional/mandatory columns.
#Hound Dog Although you was probably right i couldn't get it working the way i wanted it myself. I changed the list to of type string and was stil getting that[lorg supercsv] crap, i just decided to quit with the super csv thing, just in case anybody runs into this issue doing it like this i found to be be easier. The stuff in the constructor is not needed apart from the generate csv method
package writer;
public class RentStatementsWriter {
/*
*
* problem being that for super csv to work each entry will need a seperate list
*/
public ArrayList<RentStatements> rData;
private List<String> csvData;
char b = ',';
public RentStatementsWriter(ArrayList rentData) {
rData = rentData;
csvData = new ArrayList<String>();
try{
generateCsvFile("renttest.csv", rentData,b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print(e+" file unable to write");
} finally {
if(listWriter !=null){
try {
listWriter.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("list writer");
}
}
}
}
private void generateCsvFile(String fileName, ArrayList rentData, char b2) {
try{
final String [] header = new String []{"tncy_num", "End_Date", "bal_val","rent_val","chg_val","benf_val","adj_val","pay_val"};
FileWriter writer = new FileWriter(fileName);
writer.append("tncy_num");
writer.append(',');
writer.append("End_Date");
writer.append(',');
writer.append("bal_val");
writer.append(',');
writer.append("rent_val");
writer.append(',');
writer.append("chg_val");
writer.append(',');
writer.append("benf_val");
writer.append(',');
writer.append("adj_val");
writer.append(',');
writer.append("pay_val");
writer.append('\n');
for(int i = 0;i <rentData.size();i++){
String line = rentData.get(i).toString();
String bits []=line.split(" ");//splits each space into diffrent bits
//string something = bits.get waleva the it is surround it by ""
writer.append(bits[1]);
writer.append(b2);
writer.append(bits[2]);
writer.append(b2);
writer.append(bits[3]);
writer.append(b2);
writer.append(bits[4]);
writer.append(b2);
writer.append(bits[5]);
writer.append(b2);
writer.append(bits[6]);
writer.append(b2);
writer.append(bits[7]);
writer.append(b2);
writer.append(bits[8]);
writer.append('\n');
}
writer.flush();
writer.close();
}catch(IOException e)
{
e.printStackTrace();
}
// TODO Auto-generated method stub
}
}
Related
Converting line and column coordinate to a caret position for a JSON debugger
I am building a small Java utility (using Jackson) to catch errors in Java files, and one part of it is a text area, in which you might paste some JSON context and it will tell you the line and column where it's found it: I am using the error message to take out the line and column as a string and print it out in the interface for someone using it. This is the JSON sample I'm working with, and there is an intentional error beside "age", where it's missing a colon: { "name": "mkyong.com", "messages": ["msg 1", "msg 2", "msg 3"], "age" 100 } What I want to do is also highlight the problematic area in a cyan color, and for that purpose, I have this code for the button that validates what's inserted in the text area: cmdValidate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { functionsClass ops = new functionsClass(); String JSONcontent = JSONtextArea.getText(); Results obj = new Results(); ops.validate_JSON_text(JSONcontent, obj); String result = obj.getResult(); String caret = obj.getCaret(); //String lineNum = obj.getLineNum(); //showStatus(result); if(result==null) { textAreaError.setText("JSON code is valid!"); } else { textAreaError.setText(result); Highlighter.HighlightPainter cyanPainter; cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan); int caretPosition = Integer.parseInt(caret); int lineNumber = 0; try { lineNumber = JSONtextArea.getLineOfOffset(caretPosition); } catch (BadLocationException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } try { JSONtextArea.getHighlighter().addHighlight(lineNumber, caretPosition + 1, cyanPainter); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); } The "addHighlight" method works with a start range, end range and a color, which didn't become apparent to me immediately, thinking I had to get the reference line based on the column number. Some split functions to extract the numbers, I assigned 11 (in screenshot) to a caret value, not realizing that it only counts character positions from the beginning of the string and represents the end point of the range. For reference, this is the class that does the work behind the scenes, and the error handling at the bottom is about extracting the line and column numbers. For the record, "x" is the error message that would generate out of an invalid file. package parsingJSON; import java.io.IOException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class functionsClass extends JSONTextCompare { public boolean validate_JSON_text(String JSONcontent, Results obj) { boolean valid = false; try { ObjectMapper objMapper = new ObjectMapper(); JsonNode validation = objMapper.readTree(JSONcontent); valid = true; } catch (JsonParseException jpe){ String x = jpe.getMessage(); printTextArea(x, obj); //return part_3; } catch (IOException ioe) { String x = ioe.getMessage(); printTextArea(x, obj); //return part_3; } return valid; } public void printTextArea(String x, Results obj) { // TODO Auto-generated method stub System.out.println(x); String err = x.substring(x.lastIndexOf("\n")); String parts[] = err.split(";"); //String part 1 is the discarded leading edge that is the closing brackets of the JSON content String part_2 = parts[1]; //split again to get rid of the closing square bracket String parts2[] = part_2.split("]"); String part_3 = parts2[0]; //JSONTextCompare feedback = new JSONTextCompare(); //split the output to get the exact location of the error to communicate back and highlight it in the JSONTextCompare class //first need to get the line number from the output String[] parts_lineNum = part_3.split("line: "); String[] parts_lineNum_final = parts_lineNum[1].split(", column:"); String lineNum = parts_lineNum_final[0]; String[] parts_caret = part_3.split("column: "); String caret = parts_caret[1]; System.out.println(caret); obj.setLineNum(lineNum); obj.setCaret(caret); obj.setResult(part_3); System.out.println(part_3); } } Screenshot for what the interface currently looks like: Long story short - how do I turn the coordinates Line 4, Col 11 into a caret value (e.g. it's value 189, for the sake of argument) that I can use to get the highlighter to work properly. Some kind of custom parsing formula might be possible, but in general, is that even possible to do?
how do I turn the coordinates Line 4, Col 11 into a caret value (e.g. it's value 189, Check out: Text Utilities for methods that might be helpful when working with text components. It has methods like: centerLineInScrollPane getColumnAtCaret getLineAtCaret getLines gotoStartOfLine gotoFirstWordOnLine getWrappedLines In particular the gotoStartOfLine() method contains code you can modify to get the offset of the specified row/column.offset. The basic code would be: int line = 4; int column = 11; Element root = textArea.getDocument().getDefaultRootElement(); int offset = root.getElement( line - 1 ).getStartOffset() + column; System.out.println(offset);
The way it works is essentially counting the number of characters in each line, up until the line in which the error is occurring, and adding the caretPosition to that sum of characters, which is what the Highlighter needs to apply the marking to the correct location. I've added the code for the Validate button for context. functionsClass ops = new functionsClass(); String JSONcontent = JSONtextArea.getText(); Results obj = new Results(); ops.validate_JSON_text(JSONcontent, obj); String result = obj.getResult(); String caret = obj.getCaret(); String lineNum = obj.getLineNum(); //showStatus(result); if(result==null) { textAreaError.setText("JSON code is valid!"); } else { textAreaError.setText(result); Highlighter.HighlightPainter cyanPainter; cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan); //the column number as per the location of the error int caretPosition = Integer.parseInt(caret); //JSONtextArea.getCaretPosition(); //the line number as per the location of the error int lineNumber = Integer.parseInt(lineNum); //get the number of characters in the string up to the line in which the error is found int totalChars = 0; int counter = 0; //used to only go to the line above where the error is located String[] lines = JSONcontent.split("\\r?\\n"); for (String line : lines) { counter = counter + 1; //as long as we're above the line of the error (lineNumber variable), keep counting characters if (counter < lineNumber) { totalChars = totalChars + line.length(); } //if we are at the line that contains the error, only add the caretPosition value to get the final position where the highlighting should go if (counter == lineNumber) { totalChars = totalChars + caretPosition; break; } } //put down the highlighting in the area where the JSON file is having a problem try { JSONtextArea.getHighlighter().addHighlight(totalChars - 2, totalChars + 2, cyanPainter); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.getMessage(); } } The contents of the JSON file is treated as a string, and that's why I'm also iterating through it in that fashion. There are certainly better ways to go through lines in the string, and I'll add some reference topics on SO: What is the easiest/best/most correct way to iterate through the characters of a string in Java? - Link Check if a string contains \n - Link Split Java String by New Line - Link What is the best way to iterate over the lines of a Java String? - Link Generally a combination of these led to this solution, and I am also not targeting it for use on very large JSON files. A screenshot of the output, with the interface highlighting the same area that Notepad++ would complain about, if it could debug code: I'll post the project on GitHub after I clean it up and comment it some, and will give a link to that later, but for now, hopefully this helps the next dev in a similar situation.
How do I parse a text file to write certain lines in another text file using java?
I am learning how to work with files in Java. I have a sample file which contains key pairs and it values. I am trying to find a key pairs and if it matches, then output file would be updated with both, key pair and it's value. I am able to get key pairs in output file but unable to get values too. Stringbuilder may work here to append strings but I don't know how. Below are my input and output files. Input File: born time 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown born time 9 AM Europe -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: december Expected Output File: kingNumber 1234567890 birthmonth unknown kingNumber 1234567890 birthmonth unkbown Current Output File: kingNumber birthmonth kingNumber birthmonth I am able to write key pair ("kingNumber" and "birthmonth" in this case) to output file but I am not sure what I can do to get it's value too. String kn = "kingNumber:"; String bd = "birthmonth:"; try { File f = new File("sample.txt"); Scanner sc = new Scanner(f); FileWriter fw = new FileWriter("output.txt"); while(sc.hasNextLine()) { String lineContains = sc.next(); if(lineContains.contains(kn)) { fw.write(kn + "\n"); // This is where I am stuck. What // can I do to get it's value (number in this case). } else if(lineContains.contains(bd)) { fw.write(bd); // This is where I am stuck. What // can I do to get it's value (birthday in this case). } } } catch (IOException e) { e.printStackTrace(); }
you could use java.util.regex.Pattern & java.util.regex.Matcherwith a pattern alike: ^born\stime\s([a-zA-Z0-9\s]*)\s--\skingNumber\s(\d+)\s--\saddress:\s([a-zA-Z0-9\s/]*)\s--\sbirthmonth:\s([a-zA-Z0-9\s]*)$ write less, do more.
I have written a simple parser that it following data format from your example. You will need to call it like this: PairParser parser = new PairParser(lineContains); then you can get value from the parser by pair keys How to get value: parser.getValue("kingNumber") Note that keys do not have trailing column character. The parser code is here: package com.grenader.example; import java.util.HashMap; import java.util.Map; public class PairParser { private Map<String, String> data = new HashMap<>(); /** * Constructor, prepare the data * #param dataString line from the given data file */ public PairParser(String dataString) { if (dataString == null || dataString.isEmpty()) throw new IllegalArgumentException("Data line cannot be empty"); // Spit the input line into array of string blocks based on '--' as a separator String[] blocks = dataString.split("--"); for (String block : blocks) { if (block.startsWith("born time")) // skip this one because it doesn't looks like a key/value pair continue; String[] strings = block.split("\\s"); if (strings.length != 3) // has not exactly 3 items (first items is empty), skipping this one as well continue; String key = strings[1]; String value = strings[2]; if (key.endsWith(":")) key = key.substring(0, key.length()-1).trim(); data.put(key.trim(), value.trim()); } } /** * Return value based on key * #param key * #return */ public String getValue(String key) { return data.get(key); } /** * Return number of key/value pairs * #return */ public int size() { return data.size(); } } And here is the Unit Test to make sure that the code works package com.grenader.example; import com.grenader.example.PairParser; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class PairParserTest { #Test public void getValue_Ok() { PairParser parser = new PairParser("born time 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown"); assertEquals("1234567890", parser.getValue("kingNumber")); assertEquals("unknown", parser.getValue("birthmonth")); } #Test(expected = IllegalArgumentException.class) public void getValue_Null() { new PairParser(null); fail("This test should fail with Exception"); } #Test(expected = IllegalArgumentException.class) public void getValue_EmptyLine() { new PairParser(""); fail("This test should fail with Exception"); } #Test() public void getValue_BadData() { PairParser parser = new PairParser("bad data bad data"); assertEquals(0, parser.size()); } }
Error parsing this csv file
I am trying to parse this csv file but when i got to print it I get "Input length =1" as the output. Here is my code: Can anyone provide an explanation as to why this is happening? try { List<String> lines = Files.readAllLines(Paths.get("src\\exam1_tweets.csv")); for(String line : lines) { line = line.replace("\"", ""); System.out.println(line); } }catch (Exception e) { System.out.println(e.getMessage()); }
You want this change List<String> lines = Files.readAllLines(Paths.get("src\\exam1_tweets.csv"), StandardCharsets.ISO_8859_1); It was encoding issue please read this. To see full cause of errors you should use e.printStackTrace() in catch block.
java code: import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class Sof { public static final String USER_DIR = "user.dir"; public static void main(String[] args) { try { List<String> lines = Files.readAllLines( Paths.get(System.getProperty(USER_DIR) + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "exam1_tweets.csv"), StandardCharsets.ISO_8859_1); for (String line : lines) { line = line.replace("\"", ""); System.out.println(line); } } catch (Exception e) { System.out.println("ERROR" + e.getMessage()); } } } console: Handle,Tweet,Favs,RTs,Latitude,Longitude BillSchulhoff,Wind 3.2 mph NNE. Barometer 30.20 in, Rising slowly. Temperature 49.3 °F. Rain today 0.00 in. Humidity 32%,,,40.76027778,-72.95472221999999 danipolis,Pausa pro café antes de embarcar no próximo vôo. #trippolisontheroad #danipolisviaja Pause for? https://....,,,32.89834949,-97.03919589 KJacobs27,Good. Morning. #morning #Saturday #diner #VT #breakfast #nucorpsofcadetsring #ring #college? https://...,,,44.199476,-72.50417299999999 stncurtis,#gratefuldead recordstoredayus ?????? # TOMS MUSIC TRADE https://...,,,39.901474,-76.60681700000001 wi_borzo,Egg in a muffin!!! (# Rocket Baby Bakery - #rocketbabybaker in Wauwatosa, WI) https://...,,,43.06084924,-87.99830888 KirstinMerrell,#lyricwaters should've gave the neighbor a buzz. Iv got ice cream and moms baked goodies ??,,,36.0419128,-75.68186176 Jkosches86,On the way to CT! (# Mamaroneck, NY in Mamaroneck, NY) https://.../6rpe6MXDkB,,,40.95034402,-73.74092102 tmj_pa_retail,We're #hiring! Read about our latest #job opening here: Retail Sales Consultant [CWA MOB] Bryn Mawr PA - https://.../bBwxSPsL4f #Retail,,,40.0230237,-75.31517719999999 Vonfandango,Me... # Montgomery Scrap Corporation https://.../kpt7zM4xbL,,,39.10335,-77.13652 ....
I've made a csv parser/writer , easy to use thanks to its builder pattern It parses csv file and gives you list of beans here is the source code https://github.com/i7paradise/CsvUtils-Java8/ I've joined a main class Demo.java to display how it works let's say your file contains this Item name;price "coffe ""Lavazza""";13,99 "tea";0,00 "milk in three lines";25,50 riz;130,45 Total;158 and you want to parse it and store it into a collection of class Item { String name; double price; public Item(String name, double p) { // ... } //... } you can parse it like this: List<Item> items = CsvUtils.reader(Item.class) //content of file; or you can use content(String) to give the content of csv as a String .content(new File("path-to-file.csv")) // false to not include the first line; because we don't want to parse the header .includeFirstLine(false) // false to not include the last line; because we don't want to parse the footer .includeLastLine(false) // mapper to create the Item instance from the given line, line is ArrayList<String> that returns null if index not found .mapper(line -> new Item( line.get(0), Item.parsePrice(line.get(1))) ) // finally we call read() to parse the file (or the content) .read();
Read word from file to array and select a word randomly form array
Trying to read about 25,000 words from file and put it in arraylist and selects random word from the arraylist. Stuck at creating array, filling array, randomly selecting the word in the array. But got a weird result. Code: package se.simple; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; public class WordHandler { public static void main(String[] args) { List<String> words = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader("/Users/FOOOOO/NetBeansProjects/ss/words.txt"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { words.add(sCurrentLine); System.out.println(words); } } catch (IOException e) { e.printStackTrace(); } } } Everything is printed out in one line. But now I need to randomly select a word from arraylist. [10th, 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, a, AAA, AAAS, Aarhus, Aaron, AAU, ABA, Ababa, aback, abacus, abalone, abandon, abase, abash, abate, abater, abbas, abbe, abbey, abbot, Abbott, abbreviate, abc, abdicate, abdomen, abdominal, abduct, Abe, abed, Abel, Abelian, Abelson, Aberdeen, Abernathy, aberrant, aberrate, abet, abetted, abetting, abeyance, abeyant, abhorred, abhorrent, abide, Abidjan, Abigail, abject, ablate, ablaze, able, ablution, Abner, abnormal, Abo, aboard, abode, abolish, abolition, abominable, abominate, aboriginal, aborigine, aborning, abort, abound, about, above, aboveboard, aboveground, abovementioned, abrade, Abraham, Abram, Abramson, abrasion, abrasive, abreact, abreast, abridge, abridgment, abroad, abrogate, abrupt, abscess, abscissa, abscissae, absence, absent, absentee, absenteeism, absentia, absentminded, absinthe, absolute, absolution, absolve, absorb, absorbent, absorption, absorptive, abstain, abstention, abstinent, abstract, abstracter, abstractor, abstruse, absurd, abuilding, abundant, abusable, abuse, abusive, abut, abutted, abutting, abysmal, abyss, Abyssinia, AC, academe, academia, academic, academician, academy, Acadia, acanthus, Acapulco, accede, accelerate, accelerometer, accent, accentual, accentuate, accept, acceptant, acceptor, access, accessible, accession, accessory, accident, accidental, accipiter, acclaim, acclamation, acclimate, accolade, accommodate, accompaniment, accompanist, accompany, accomplice, accomplish, accord, accordant, accordion, accost, account, accountant, Accra, accredit, accreditate, accreditation, accretion, accrual, accrue, acculturate, accumulate, accuracy, accurate, accusation, accusative, accusatory, accuse, accustom, ace, acerbic, acerbity, acetate, acetic, acetone, acetylene, ache, achieve, Achilles, aching, achromatic, acid, acidic, acidulous, Ackerman, Ackley, acknowledge, acknowledgeable, ACM, acme, acolyte, acorn, acoustic, acquaint, acquaintance, acquiesce, acquiescent, acquire, acquisition, acquisitive, acquit, acquittal, acquitting, acre, acreage, acrid, acrimonious, acrimony, acrobacy, acrobat, acrobatic, acronym, acropolis, across, acrylate, acrylic, ACS, act, Actaeon, actinic, actinide, actinium, actinolite, actinometer, activate, activation, activism, Acton, actor, actress, Acts, actual, actuarial, actuate, acuity, acumen, acute, acyclic, ad, Ada, adage, adagio, Adair, Adam, adamant, Adams, Adamson, adapt, adaptation, adaptive, add, added, addend, addenda, addendum, addict, Addis, Addison, addition, additional, additive, addle, address, addressee, Addressograph, adduce, Adelaide, Adele, Adelia, Aden, adenine, adenoma, adenosine, adept, adequacy, adequate, adhere, adherent, adhesion, adhesive, adiabatic, adieu, adipic, Adirondack, adjacent, adject, adjectival, adjective, adjoin, adjoint, adjourn, adjudge, adjudicate, adjunct, adjust, adjutant, Adkins, Adler, administer, administrable, administrate, administratrix, admiral, admiralty, admiration, admire, admissible, admission, admit, admittance, admitted, admitting, admix, admixture, admonish, admonition, ado, adobe, adolescent, Adolph, Adolphus, Adonis, adopt, adoption, adoptive, adore, adorn, adposition, adrenal, adrenaline, Adrian, Adriatic, Adrienne, adrift, adroit, adsorb, adsorbate, adsorption, adsorptive, adulate, adult, adulterate, adulterous, adultery, adulthood, advance, advantage, advantageous, advent, adventitious, adventure, adventurous, adverb, adverbial, adversary, adverse, advert, advertise, advice, advisable, advise, advisee, advisor, advisory, advocacy, advocate, Aegean, aegis, Aeneas, Aeneid, aeolian, Aeolus, aerate, aerial, Aerobacter, aerobic, aerodynamic, aerogene, aeronautic, aerosol, aerospace, Aeschylus, aesthete, aesthetic, afar, affable, affair, affect, affectate, affectation, affectionate, afferent, affiance, affidavit, affiliate, affine, affinity, affirm, affirmation, affirmative, affix, afflict, affluence, affluent, afford, afforest, afforestation, affricate, affront, Afghan, Afghanistan, aficionado, afield, afire, aflame, afloat, afoot, aforementioned, aforesaid, aforethought, afoul, afraid, afresh, Africa, afro, aft, aftereffect, afterglow, afterimage, afterlife, aftermath, afternoon, afterthought, afterward, afterword, again, against, Agamemnon, agate, Agatha, agave, age, Agee, agenda, agent, agglomerate, agglutinate, agglutinin, aggravate, aggregate, aggression, aggressive, aggressor, aggrieve, aghast, agile, aging, agitate, agleam, Agnes, Agnew, BUILD STOPPED (total time: 30 seconds)
Hmm I don't want to just do this all for you. It seems like it's an assignment. I will however give a template for how you could do it. Create a method that just reads in the words file to an array list of words. Create a method that randomly picks an element from your list of words. In your main method call on method 1 to create your word list. Call on method 2 as many times as you need to in order to print off enough random words.
look at this 2 things and try to modify this code that i wrote. How do I generate random integers within a specific range in Java? String array initialization in Java BufferedReader br = null; String words[] = new String[4]; int i=0; try { String sCurrentLine; String word; br = new BufferedReader(new FileReader("/Users/FOOOOO/NetBeansProjects/ss/words.txt")); while ((sCurrentLine = br.readLine()) != null) { words[i]=sCurrentLine; i++; } Random rn = new Random(); int x = rn.nextInt(3)+1; System.out.println(words[x]); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { ex.printStackTrace(); } }
package se.simple; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; public class WordHandler { public static void main(String[] args) { //1. Create an array List<String> words = new ArrayList<String>(); //2. Read a file line by line and add file words to words array. try (BufferedReader br = new BufferedReader(new FileReader("/Users/FOOOOO/NetBeansProjects/ss/words.txt"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { words.add(sCurrentLine); //System.out.println(words); } System.out.println(words); } catch (IOException e) { e.printStackTrace(); } System.out.println(words.size()); //3. Randomizing to pick up a word from arraylist Random rand = new Random(); int randomNumber = rand.nextInt(words.size() - 1) + 1; System.out.println(randomNumber); //4. Prints the randomly selected word. String word = words.get(randomNumber); System.out.println(word); //5. Gets the word length. int dashedWord = word.length(); System.out.println(dashedWord); //6. Prints the word as dashes. for(int x = 0; x < dashedWord; x = x+1) { System.out.print("-"); } } }
Reading a formatted text file + Extracting certain information + Loading it into a JList
So here I got my code that would read a text file: import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; public class ReadTextFile { public static void main(String[] args) { File file = new File("Test.txt"); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String text = null; // repeat until all lines is read while ((text = reader.readLine()) != null) { contents.append(text).append(System.getProperty("line.separator")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } // show file contents here System.out.println(contents.toString()); } } Ok, now I need my text file (Test.txt) to have the following structure (Example): topic:- <climate>subtopic1, <atmosphere_type>subtopic2 subtopic1:- <temperatures>sentence1, <gases>sentence2, <winds>sentence3 subtopic2:- <gas_composition>sentence4, <gravitational_weight>sentence5 sentence1:- temperatures are around 34ºC but they can reach -42ºC in winter sentence2:- there are significant proportions of nitrogen (13%) and butane (24%) sentence3:- there are permanent winds with gusts of 118 km/h sentence4:- methane (48%), nitrogen (13%), butane (24%) and oxygen (12%) sentence5:- gravity in ecuador is 7.95 atmospheres What I really need is to have 2 JList, where in the first JList I could choose a topic (Like "climate" or "atmosphere type") and then on my second JList I'd select a subtopic (If I choose "climate", then I could choose "temperatures", "gases" or "winds"), so when I hit a JButton, the program would show me the corresponding sentence. Is it hard to do something like that? Thanks for your help! :)
Try to build the following data structures from the file. // map of a topic (or subtopic) name to a list of subtopic (or sentence) names Map<String, List<String>> subtopics = new HashMap<String, List<String>>(); // The above will contain the entries: // topic -> [subtopic1, subtopic2] // subtopic1 -> [sentence1, sentence2, sentence3] // subtopic2 -> [sentence4, sentence5] // map of topic/sentence name to heading Map<String, String> headings = new HashMap<String, String>(); // This will contain: // subtopic1 -> climate // subtopic2 -> atmosphere type // sentence1 -> temperatures // sentence2 -> gases // sentence3 -> winds // sentence4 -> gas composition // sentence5 -> gravitational weight // dictionary for looking up a sentence name and retrieving its corresponding text Map<String, String> dict = new HashMap<String, String>(); // sentence1 -> temperatures are around 34ºC but they can reach -42ºC in winter // sentence2 -> there are significant proportions of nitrogen (13%) and butane (24%) // sentence3 -> there are permanent winds with gusts of 118 km/h // sentence4 -> methane (48%), nitrogen (13%), butane (24%) and oxygen (12%) // sentence5 -> gravity in ecuador is 7.95 atmospheres This should get you going in a good direction. One bit to watch for is when adding a topic to the 'subtopics' map for the first time, you have to remember to first create the List (e.g. an ArrayList), add the subtopic name to the list and and the list as the value for the topic name. If the topic name is found in the list, just add the subtopic name to the existing List.