import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.ArrayList;
/**
* Write a description of class ReadInCsv here.
*
* #author (Kevin Knapp)
* #version (10-10-2013)
*/
public class ReadInCsv
{
public static void main(String[] args)
{
String csvName = "Countries.csv";
File csvFile = new File(csvName);
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> popList = new ArrayList<>();
ArrayList<String> areaList = new ArrayList<>();
ArrayList<String> gdpList = new ArrayList<>();
ArrayList<String> litRateList = new ArrayList<>();
try
{
Scanner in = new Scanner(csvFile).useDelimiter(",");
while (in.hasNext())
{
String name = in.next();
nameList.add(name);
String pop = in.next();
popList.add(pop);
String area = in.next();
areaList.add(area);
String gdp = in.next();
gdpList.add(gdp);
String litRate = in.next();
litRateList.add(litRate);
}
in.close();
System.out.println(nameList);
System.out.println(popList);
System.out.println(areaList);
System.out.println(gdpList);
System.out.println(litRateList);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
So im trying to read from a csv file and as it goes through it should add each scanned instance into a array list (im going to reference each element from these lists at a later point), but my outputs show that as soon as it reads something and adds it, it skips to the next line before reading the next string, i need it to read straight across, not diagonally
im sure im just missing something very simple, I just began learning java about a week ago, thanks for the help
A big problem with this method is that unless each line in the file ends in a comma, newlines will not be delimited. A better way is to read each line in, split on commas, and add the values to the ArrayLists one line at a time:
Scanner in = new Scanner(csvFile);
while (in.hasNextLine()) {
String[] fields = in.nextLine().split(",");
if (fields.length == 5) {
nameList.add(fields[0]);
popList.add(fields[1]);
areaList.add(fields[2]);
gdpList.add(fields[3]);
litRateList.add(fields[4]);
} else {
// Bad line...do what you want to show error here
}
}
An even better way is to use a Java library dedicated to reading CSV files. A quick Google search should turn up some good ones.
Related
I am trying to parse a text document that has release notes and grab specific ones. To do that I have a csv with the desired release note keys. I want to scan the csv and use each key to find the matching section of the release note, and print the description that follows.
I would like to use the Scanner class for this to practice with it.
The csv looks like:
foobar-123,foobar-127,foobar-129
The release note text doc looks like:
foobar-123: ewkjhlq kghlhrekgh
foobar-124: lkjhfgrelgkj nberg
foobar-127: ljdfgl kjwneglkjn fdg
foobar-129: lguwlrkguj gwrlekgj werlktj
The issue I am running into is iterating through the csv. I seem to keep grabbing the first string in the csv. I am trying to figure out how to save my place in the csv, so every time the method is called, it goes to the next string.
I'm thinking I could create a variable that saves the last found string, and then use scanner to find that and then grab the next string. But that would require scanning through the csv each time I want to progress and which does not seem efficient. What would be the best way to iterate through the csv using the Scanner class?
Here is the code I have so far:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class ReleaseNotesScan {
public static void main(String[] args) {
//Open csv file with issue keys
Scanner getIssueKeys = null;
try {
getIssueKeys = new Scanner(new FileReader("resources/Issues.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Open release notes
Scanner releaseNotes = null;
try {
releaseNotes = new Scanner(new FileReader("resources/Release notes text.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Get issue key from csv
String issueKey = Finders.issueKey(getIssueKeys);
//The below three lines are just for testing if I am iterating through the csv
System.out.println(issueKey);
Finders.issueKey(getIssueKeys);
System.out.println(issueKey);
//Get issue key and description
String description = Finders.sectionContent(releaseNotes, issueKey);
System.out.println(issueKey + ": " + description);
//Close csv
getIssueKeys.close();
//Close release notes
releaseNotes.close();
}
}
My Finders class:
import java.util.Scanner;
public class Finders {
//parse csv
public static String issueKey(Scanner findIssues) {
findIssues.useDelimiter(",");
String issue = findIssues.next();
return issue;
}
public static String sectionContent(Scanner releaseNotes, String heading) {
while (releaseNotes.hasNextLine()){
String found = releaseNotes.findInLine(heading);
if (found != null){
releaseNotes.findInLine(": ");
String grabIt = releaseNotes.nextLine();
return grabIt;
}
releaseNotes.nextLine();
}
releaseNotes.close();
return "Not found";
}
}
Here is some example code to demonstrate how the application can be structured. I made some assumptions that the input file "issues" as a string (instead of a file, for brevity). The issues are stored in an array and release notes in HashMap collection. The release notes are read from the file, tokenized (split with ":" as delimiter) as the issue and its release-note text. The issue is the key and the release-note is the value in the map.
Finally, iterate each issue and get the corresponding release-note from the map.
Example Code:
import java.util.*;
import java.io.*;
public class MatchIssues {
private static String [] issues;
private static Map<String,String> releseNotes = new HashMap<>();
public static void main(String [] args)
throws IOException {
getIssues();
getReleaseNotes();
for(String issue : issues) {
// Match release notes for the issue
System.out.println(releseNotes.get(issue));
}
}
private static void getIssues() {
String s = "foobar-123,foobar-127,foobar-129"; // use string for demo
issues = s.split(",");
System.out.println(Arrays.toString(issues));
}
private static void getReleaseNotes()
throws IOException {
BufferedReader reader =
new BufferedReader(new FileReader("release_notes.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
String [] tokens = line.split(":");
releseNotes.put(tokens[0].trim(), tokens[1].trim());
}
System.out.println(releseNotes);
}
}
release_notes.txt:
foobar-123: aa ewk jhlq kghlhrekgh aa
foobar-124: bb lkjh fgrelgkj nberg bb
foobar-127: yy ljdfgl kjw neglkjn fdg yy
foobar-129: zz lgu wlrkguj gw rlekgj werlktj zz
I know there are many questions about reading text files here but I have gone through all of them and I think I'm having some difficulty with syntax or SOMETHING because nothing that I've been trying has been working at all.
What I'm attempting to do is this:
1) read a text file inputed by user
2) copy each individual line into an array, so each line is its own element in the array
I feel like I am very close but for some reason I can't figure out exactly how to get it to work!
Here is the relevant code I have right now:
I keep getting out of bounds exceptions in three locations which I've marked off.
Been working on this for quite a while not sure what to do next! Any ideas?
import java.io.IOException;
import java.util.Scanner;
public class FindWords {
public static void main (String args[]) throws IOException{
FindWords d = new Dictionary();
((Dictionary) d).dictionary(); //********* out of bounds here
}
/**
* Validates and returns the dictionary inputed by the user.
*
* #param
* #return the location of the dictionary
*/
public static String getDict(){
///////////////////ASK FOR DICTIONARY////////////////////
System.out.println("Please input your dictionary file");
//initiate input scanner
Scanner in = new Scanner(System.in);
// input by user
String dictionary = in.nextLine();
System.out.println("Sys.print: " + dictionary);
//make sure there is a dictionary file
if (dictionary.length() == 0){
throw new IllegalArgumentException("You must enter a dictionary");
}
else return dictionary;
}
}
which calls on the class Dictionary:
import java.io.*;
public class Dictionary extends FindWords{
public void dictionary () throws IOException{
String dict = getDict();
String[] a = readFile(dict); //********** out of bounds here
int i = 0;
while(a[i] != null){
System.out.println(a[i]);
i++;
}
}
public static String[] readFile(String input) throws IOException{
//read file
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
System.out.println ();
int count = 0;
String[] array = new String[count];
try{
while (br.readLine() != null){
array[count] = br.readLine(); //********out of bounds here
count++;
}
br.close();
}
catch (IOException e){
}
return array;
}
}
Thank you for looking!
Edit: Just fyi: I have my .txt file in the parent project folder.
Have you tried this?:
List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));
and then transform your list to an array if you want:
String[] myLines = lines.toArray(new String[lines.size()]);
You start with an array size of zero...
int count = 0;
String[] array = new String[count];
Several issues here :
In Java, you can't expand arrays, i.e you have to know their length in advance when you instantiate them. Hence the ArrayOutOfBoundException. To make this easy, I suggest that you use an ArrayList instead.
In your while loop, you're making 2 calls to br.readLine(), so basically you're skipping one line out of 2.
You are initializing a zero-length array, hence the exception on the first iteration:
int count = 0;
String[] array = new String[count];
Since you probably don't know the expected size, work with a List instead:
List<String> list = new ArrayList<>();
String thisLine = null;
try{
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
}
You can get the total size afterwards by:
list.size();
Or even better, go with morganos solution and use Files.readAllLines().
Importing a large list of words and I need to create code that will recognize each word in the file. I am using a delimiter to recognize the separation from each word but I am receiving a suppressed error stating that the value of linenumber and delimiter are not used. What do I need to do to get the program to read this file and to separate each word within that file?
public class ASCIIPrime {
public final static String LOC = "C:\\english1.txt";
#SuppressWarnings("null")
public static void main(String[] args) throws IOException {
//import list of words
#SuppressWarnings("resource")
BufferedReader File = new BufferedReader(new FileReader(LOC));
//Create a temporary ArrayList to store data
ArrayList<String> temp = new ArrayList<String>();
//Find number of lines in txt file
String line;
while ((line = File.readLine()) != null)
{
temp.add(line);
}
//Identify each word in file
int lineNumber = 0;
lineNumber++;
String delimiter = "\t";
//assess each character in the word to determine the ascii value
int total = 0;
for (int i=0; i < ((String) line).length(); i++)
{
char c = ((String) line).charAt(i);
total += c;
}
System.out.println ("The total value of " + line + " is " + total);
}
}
This smells like homework, but alright.
Importing a large list of words and I need to create code that will recognize each word in the file. What do I need to do to get the program to read this file and to separate each word within that file?
You need to...
Read the file
Separate the words from what you've read in
... I don't know what you want to do with them after that. I'll just dump them into a big list.
The contents of my main method would be...
BufferedReader File = new BufferedReader(new FileReader(LOC));//LOC is defined as class variable
//Create an ArrayList to store the words
List<String> words = new ArrayList<String>();
String line;
String delimiter = "\t";
while ((line = File.readLine()) != null)//read the file
{
String[] wordsInLine = line.split(delimiter);//separate the words
//delimiter could be a regex here, gotta watch out for that
for(int i=0, isize = wordsInLine.length(); i < isize; i++){
words.add(wordsInLine[i]);//put them in a list
}
}
You can use the split method of the String class
String[] split(String regex)
This will return an array of strings that you can handle directly of transform in to any other collection you might need.
I suggest also to remove the suppresswarning unless you are sure what you are doing. In most cases is better to remove the cause of the warning than supress the warning.
I used this great tutorial from thenewboston when I started off reading files: https://www.youtube.com/watch?v=3RNYUKxAgmw
This video seems perfect for you. It covers how to save file words of data. And just add the string data to the ArrayList. Here's what your code should look like:
import java.io.*;
import java.util.*;
public class ReadFile {
static Scanner x;
static ArrayList<String> temp = new ArrayList<String>();
public static void main(String args[]){
openFile();
readFile();
closeFile();
}
public static void openFile(){
try(
x = new Scanner(new File("yourtextfile.txt");
}catch(Exception e){
System.out.println(e);
}
}
public static void readFile(){
while(x.hasNext()){
temp.add(x.next());
}
}
public void closeFile(){
x.close();
}
}
One thing that is nice with using the java util scanner is that is automatically skips the spaces between words making it easy to use and identify words.
I just started to code a while back and I'm in the process of dealing with arrays on my own, I understand them in theory but I need some help when it comes to getting practical. I asked my instructor to give me a couple of practices problems and he gave me the following.
using this as your main:
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras( "words.txt" );
JOptionPane.showMessageDialog(null, datos );
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
(its in spanish so bear with me) create a class named DatosPalabras and words.txt and make sure your code can:
Read and display words.txt
Display the words in "words.txt" in alphabetical order
I really appreciate the help, I'm a bit stumped but I'm curious to know how I can accomplish this. Thank you!
EDIT:
public class DatosPalabras {
public DatosPalabras(String string) {
// read and display the content of words.txt
}
public void sort() {
// need info on what to use in order to sort words instead of doubles and integers.
}
}
In this example I have 1 file named Q19505617.java. Java only allows you to have 1 public class per file. It is the class that defines the main method. So this example works only because the DatosPalabras class is contained in that file. If you need DatosPalabras to be its own class then put the DatosPalabras in its own file named DatosPalabras.java and change the class signature to be public class DatosPalabras.
import java.io.InputStream;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Q19505617 {
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras("words.txt");
JOptionPane.showMessageDialog(null, datos);
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
}
class DatosPalabras {
private String[] lines;
public DatosPalabras(String filename) {
lines = new String[1];
int lineCounter = 0;
InputStream in = Q19505617.class.getResourceAsStream(filename);
Scanner scanner = new Scanner(in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
if(lineCounter == lines.length) {
lines = Arrays.copyOf(lines, lines.length * 2);
}
lines[lineCounter] = line;
lineCounter++;
}
}
public void sort() {
// put your real sort algorithm here. until then use this:
}
public String toString() {
StringBuilder b = new StringBuilder();
for (String line : lines) {
b.append(line).append("\n");
}
return b.toString();
}
}
You can create a reading Array like this:
String[] Array = new String[number of lines in you txt file];
int i = 0;
// Selecting the txt file
File theFile = new File("bla.txt");
//Creating a scanner to read the file
scan = new Scanner(theFile);
//Reading all the words from the txt file
while (scan.hasNextLine()) {
line = scan.nextLine();
Array[i] = line; // gets all the lines
i++;
Then you create a method for sorting.
I have this programming assignment and it is the first time in our class that we are writing code in Java. I have asked my instructor and could not get any help.
The program needs to count word pairs from a file, and display them like this:
abc:
hec, 1
That means that there was only one time in the text file that "abc" was followed by "hec". I have to use the Collections Framework in java. Here is what I have so far.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ArrayList;
// By default, this code will get its input data from the Java standard input,
// java.lang.System.in. To allow input to come from a file instead, which can be
// useful when debugging your code, you can provide a file name as the first
// command line argument. When you do this, the input data will come from the
// named file instead. If the input file is in the project directory, you will
// not need to provide any path information.
//
// In BlueJ, specify the command line argument when you call main().
//
// In Eclipse, specify the command line argument in the project's "Run Configuration."
public class Assignment1
{
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName)
{
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
System.err.println(e.getMessage());
inputStream = null;
}
return inputStream;
}
public static void main(String[] args)
{
// Create an input stream for reading the data. The default is
// System.in (which is the keyboard). If there is an arg provided
// on the command line then we'll use the file instead.
InputStream in = System.in;
if (args.length >= 1) {
in = getFileInputStream(args[0]);
}
// Now that we know where the data is coming from we'll start processing.
// Notice that getFileInputStream could have generated an error and left "in"
// as null. We should check that here and avoid trying to process the stream
// data if there was an error.
if (in != null) {
// Using a Scanner object to read one word at a time from the input stream.
#SuppressWarnings("resource")
Scanner sc = new Scanner(in);
String word;
System.out.printf("CS261 - Assignment 1 - Matheus Konzen Iser%n%n");
// Continue getting words until we reach the end of input
List<String> inputWords = new ArrayList<String>();
Map<String, List<String>> result = new HashMap<String, List<String>>();
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
for(int i = 0; i < inputWords.size() - 1; i++){
// Create references to this word and next word:
String thisWord = inputWords.get(i);
String nextWord = inputWords.get(i+1);
// If this word is not in the result Map yet,
// then add it and create a new empy list for it.
if(!result.containsKey(thisWord)){
result.put(thisWord, new ArrayList<String>());
}
// Add nextWord to the list of adjacent words to thisWord:
result.get(thisWord).add(nextWord);
}
//OUTPUT
for(Entry e : result.entrySet()){
System.out.println(e.getKey() + ":");
// Count the number of unique instances in the list:
Map<String, Integer>count = new HashMap<String, Integer>();
List<String>words = (List)e.getValue();
for(String s : words){
if(!count.containsKey(s)){
count.put(s, 1);
}
else{
count.put(s, count.get(s) + 1);
}
}
// Print the occurances of following symbols:
for(Entry f : count.entrySet()){
System.out.println(" " + f.getKey() + ", " + f.getValue());
}
}
}
System.out.printf("%nbye...%n");
}
}
}
The problem that I'm having now is that it is running through the loop below way too many times:
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
Does anyone have any ideas or tips on this?
I find this part confusing:
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
for(int i = 0; i < inputWords.size() - 1; i++){
I think you probably mean something more like this:
// Add all words (other than "---") into inputWords
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
inputWords.add(word);
}
}
// Now iterate over inputWords and process each word one-by-one
for (int i = 0; i < inputWords.size(); i++) {
It looks like you're trying to read all the words into inputWords first and then process them, while your code iterates through the list after every word that you add.
Note also that your condition in the for loop is overly-conservative, so you'll miss the last word. Removing the - 1 will give you an index for each word.