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();
Related
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());
}
}
I got this error message happening when I'm trying to read a csv:
Exception in thread "main" java.lang.IllegalStateException: No header mapping was specified, the record values can't be accessed by name
at org.apache.commons.csv.CSVRecord.get(CSVRecord.java:99)
at mockdata.MockData.main(MockData.java:33)
Java Result: 1
I'm using Apache Commons CSV library 1.1. Tried googling the error message and the only thing I get is the code listing on sites like grepcode.
Here's my code:
package mockdata;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
public class MockData
{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException
{
Reader in = new InputStreamReader(MockData.class.getClassLoader()
.getResourceAsStream("MOCK_DATA.csv"), "UTF-8");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records)
{
String lastName = record.get("last_name");
String firstName = record.get("first_name");
System.out.println("firstName: " + firstName + " lastName: " + lastName);
}
}
}
The contents of CSV:
first_name,last_name,address1,city,state,zip,country,phone,email
Robin,Lee,668 Kinsman Road,Hagerstown,TX,94913,United States,5-(078)623-0713,rlee0#e-recht24.de
Bobby,Moreno,68 Dorton Avenue,Reno,AZ,79934,United States,5-(080)410-6743,bmoreno1#ihg.com
Eugene,Alexander,3 Bunker Hill Court,Newark,MS,30066,United States,5-(822)147-6867,ealexander2#gmpg.org
Katherine,Crawford,3557 Caliangt Avenue,New Orleans,OR,23289,United States,2-(686)178-7222,kcrawford3#symantec.com
It's located in my src folder.
Calling withHeader() to the default Excel CSV format worked for me:
CSVFormat.EXCEL.withHeader().parse(in);
The sample in the documentation is not very clear, but you can found it here
:
Referencing columns safely:
If your source contains a header record, you can simplify your code and safely reference columns, by using withHeader(String...) with no arguments:
CSVFormat.EXCEL.withHeader();
this worked for me
try (Reader in = new FileReader(f);
CSVParser parser = new CSVParser(in,
CSVFormat.EXCEL.withDelimiter(';').withHeader("Assembly Item Number", "Material Type", "Item Name", "Drawing Num", "Document Type", "Revision", "Status", "Drawing name",
"BOM Material Type", "Component Name"));) {
for (CSVRecord record : parser) {
System.out.println(record.get("Item Name"));
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
With version 1.9.0 withHeader() is now deprecated and the guide hasn't been updated. You're supposed to use this pattern: CSVFormat.RFC4180.builder().setHeader("a","b","c").build().parse(in)
I managed to ignore the space in the header name (in between) using the following code - by using the get(index) instead of get("header_name"). And also, stop reading the csv when blank value/row is detected:
CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(br);
for (CSVRecord record : csvParser) {
String number= record.get(0);
String date = record.get("date");
String location = record.get("Location");
String lsFile = record.get(3);
String docName = record.get(4);
if(StringUtils.isEmpty(lsFile)) {
break;
}
}
you need to get a look a the definition of every format in this URL
to define the format of your file
try this :
File f = new File("your path file ");
Reader readfile = new FileReader(f);
Iterable<CSVRecord> records = CSVFormat.DEFAULT.withDelimiter(';').withHeader().parse(readfile);
I have a program that extracts certain elements(article author names) from many articles, from the PubMed site. While the program works correctly in my pc (windows), when i try to run it on unix returns an empty list. I suspect this is because the syntax should be somewhat different in a unix system. The problem is the JSoup documentation does not mention something. Anyone know anything on this? My code is something like this:
Document doc = Jsoup.connect("http://www.ncbi.nlm.nih.gov/pubmed/" + pmidString).timeout(60000).userAgent("Mozilla/25.0").get();
System.out.println("connected");
Elements authors = doc.select("div.auths >*");
System.out.println("number of elements is " + authors.size());
The final System.out.println always says the size is 0 therefore it cannot do anything more.
Thanks in advance
Complete Example:
protected static void searchLink(HashMap<String, HashSet<String>> authorsMap, HashMap<String, HashSet<String>> reverseAuthorsMap,
String fileLine
) throws IOException, ParseException, InterruptedException
{
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(fileLine.substring(0, fileLine.length() - 1 ));
String pmidString = (String)jsonObj.get("pmid");
System.out.println(pmidString);
Document doc = Jsoup.connect("http://www.ncbi.nlm.nih.gov/pubmed/" + pmidString).timeout(60000).userAgent("Mozilla/25.0").get();
System.out.println("connected");
Elements authors = doc.select("div.auths >*");
System.out.println("found the element");
HashSet<String> authorsList = new HashSet<>();
System.out.println("authors list hashSet created");
System.out.println("number of elements is " + authors.size());
for (int i =0; i < authors.size(); i++)
{
// add the current name to the names list
authorsList.add(authors.get(i).text());
// pmidList variable
HashSet<String> pmidList;
System.out.println("stage 1");
// if the author name is new, then create the list, add the current pmid and put it in the map
if(!authorsMap.containsKey(authors.get(i).text()))
{
pmidList = new HashSet<>();
pmidList.add(pmidString);
System.out.println("made it to searchLink");
authorsMap.put(authors.get(i).text(), pmidList);
}
// if the author name has been found before, get the list of articles and add the current
else
{
System.out.println("Author exists in map");
pmidList = authorsMap.get(authors.get(i).text());
pmidList.add(pmidString);
authorsMap.put(authors.get(i).text(), pmidList);
//authorsMap.put((String) authorName, null);
}
// finally, add the pmid-authorsList to the map
reverseAuthorsMap.put(pmidString, authorsList);
System.out.println("reverseauthors populated");
}
}
I have a thread pool, and each thread uses this method to populate two maps. The fileline argument is a single line that I parse as json and keep the "pmid" field. Using this string I access the url of this article, and parse the HTML for the names of the authors. The rest should work (it does work in my pc), but because the authors.size is 0 always, the for directly below the number of elements System.out does not get executed at all.
I've tried an example doing exactly what you're trying:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class Test {
public static void main (String[] args) throws IOException {
String docId = "24312906";
if (args.length > 0) {
docId = args[0];
}
String url = "http://www.ncbi.nlm.nih.gov/pubmed/" + docId;
Document doc = Jsoup.connect(url).timeout(60000).userAgent("Mozilla/25.0").get();
Elements authors = doc.select("div.auths >*");
System.out.println("os.name=" + System.getProperty("os.name"));
System.out.println("os.arch=" + System.getProperty("os.arch"));
// System.out.println("doc=" + doc);
System.out.println("authors=" + authors);
System.out.println("authors.length=" + authors.size());
for (Element a : authors) {
System.out.println(" author: " + a);
}
}
}
My OS is Linux:
# uname -a
Linux graphene 3.11.0-13-generic #20-Ubuntu SMP Wed Oct 23 07:38:26 UTC 2013 x86_64 x86_64 x86_64
GNU/Linux
# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 13.10
Release: 13.10
Codename: saucy
Running that program produces:
os.name=Linux
os.arch=amd64
authors=Liu W
Chen D
authors.length=2
author: Liu W
author: Chen D
Which seems to work. Perhaps the issue is with fileLine? Can you print out the value of 'url':
System.out.println("url='" + "http://www.ncbi.nlm.nih.gov/pubmed/" + pmidString+ "'");
Since you're not getting an exception from your code, I suspect you're getting a document, just not one your code is anticipating. Printing out the document so you can see what you've gotten back will probably help as well.
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
}
}
I am trying to get a project finished but am having no luck. It is an online course so my only communication is through email. He has yet to reply to my four emails over the last five days.
So for this assignment we had to download a csv file from containing NASDAQ stock price info for a specific company. I chose GOOG (google). Below are the requirements for the code portion.
Create a second file ReadFiles.java. This is the file that will read in the data from your csv file. Note: You will want to use a smaller version of your data file (20 rows) for testing.
Your ReadFiles.java class requires the following methods:
Method: check to see if the file exists
Method: find number of rows in csv file
Method: Converts the csv file to a mutli-dimensional array
Method: PrintArray
Method: Return array using a get method
Create a file DataAnalyzer.java. This file will be used to call the methods in ReadFiles.java. Be sure to demonstrate that all of your methods work through DataAnalyzer.java.
This is what I have so far.
package Analysis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.StringTokenizer;
import java.util.Scanner;
public class ReadFiles
{
public static int numberOfRows;
public static int rowNumber = 0;
public static int columnNumber = 0;
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
String fileName;
System.out.print("Enter the file name >> ");
fileName = kb.nextLine();
File f = new File("D:\\Java\\Assignment 3\\" + fileName);
if(f.exists())
{
System.out.print("File exists.");
}
fileName="D:\\Java\\Assignment 3\\" + fileName;
try
{
BufferedReader br = new BufferedReader(new FileReader(fileName));
StringTokenizer st = null;
while((fileName = br.readLine()) != null)
{
rowNumber++;
numberOfRows++;
st = new StringTokenizer(fileName, ",");
while(st.hasMoreTokens())
{
columnNumber++;
System.out.println("Row " + rowNumber +
", Column " + columnNumber
+ ", Entry : "+ st.nextToken());
}
columnNumber = 0;
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void rows()
{
System.out.println("Total Rows: " + numberOfRows);
}
}
The book we have been given for the course is no help. All of the "Examples" and "You do it" portions give errors. Also in the entire chapter this assignment is based on, not one mention of an array.
When I run this code I do not get any error. I am shown the following:
File exists.
Row 1, Column 1, Entry : 30/12/2011
Row 1, Column 2, Entry : 642.02
Row 1, Column 3, Entry : 646.76
Row 1, Column 4, Entry : 642.02
Row 1, Column 5, Entry : 645.9
Row 1, Column 6, Entry : 1782300
Row 1, Column 7, Entry : 645.9
Row 2, Column 1, Entry : 29/12/2011
Row 2, Column 2, Entry : 641.49
I am shown from row 1 - 19 (the entire file).
What I do not understand is how to create separate methods in this class to convert to an array, print the array, and return the array.
Any help would be much appreciated.
Thanks
You need to define 2 classes, DataAnalyzer and ReadFiles. You usually have one file per class, although this is not a requirement. The structure of ReadFiles has been provided, so you will have a file called ReadFiles.java like this:
public class ReadFiles{
//instance var(s)
...
//constructor(s)
...
//methods(s)
/**
* Checks whether the file exists
*/
public boolean exists(){
....
}
/*
* Number of rows in the file
*/
public int getRowCount(){
....
}
// add the rest your self!!
}
}
You'll also need a file called DataAnalyzer.java:
public class DataAnalyzer{
public static void main(String args){
//create ReadFiles and call it's methods and check they return what is expected
}
}
Assume the ReadFile manages a single input file; it probably needs a class variable to hold that information. The DataAnalyzer will need to tell the ReadFiles which file to analyse (a constructor seems a good choice).
My advice is to create your skeleton structure (you already have been told what it is) and start building the functionality of each method one at a time.