I keep getting this same exception when I compile. Can anyone explain why I keep getting this error and what it means or what I need to do?
I would like to know what I am doing wrong for future references.
public static void Second()
{
int n = stringList.listSize();
for(int i=0; i<n-1; i=i+2)
{
System.out.println(stringList.retrieveAt(i) + " " + stringList.retrieveAt(i+1));
}
}
public static void Display()throws IOException, FileNotFoundException
{
Scanner infile = new Scanner(new FileReader("D:\\DataFile.txt"));
StringTokenizer token = new StringTokenizer(infile.nextLine());
StringElement str = new StringElement();
while(infile.hasNext())
{
str.setString(token.nextToken());
stringList.insert(str);
}
stringList.print();
}
The exception:
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at Programmmmmm.Display(Programmmmmm.java:121)
at Programmmmmm.main(Programmmmmm.java:67)
You're calling token.nextToken() without checking whether there are in fact more tokens in token.
Instead of checking whether there infile has more elements, you should check whether token has more tokens.
Instead of
while (infile.hasNext()) { ...
You should do
while (token.hasMoreTokens()) { ...
See Oracle's Java documentation on StringTokenizer for more information and code examples.
You're crossing the streams.
You're looping over the Scanner, but checking nextToken() on the StringTokenizer.
You aren't following the Sun Java coding standards: method names should start with a lower case letter.
That one method is doing far too much:
Reading a hard coded file path.
Tokenizing each line
Printing a list of strings.
Bad idea.
Try something more like this:
public static List<String> tokenizeTextFile(String path) throws IOException, FileNotFoundException {
List<String> words = new ArrayList<String>();
BufferedReader br = null;
if (path != null && path.length() > 0) {
try {
br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.nextLine()) != null) {
String [] tokens = line.split("\\s+");
for (String token : tokens) {
words.add(token);
}
} finally {
close(br); // add this method.
}
}
return words;
}
Related
I am new in java. I just wants to read each string in java and print it on console.
Code:
public static void main(String[] args) throws Exception {
File file = new File("/Users/OntologyFile.txt");
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(
fstream));
String data = new String();
while ((data = infile.readLine()) != null) { // use if for reading just 1 line
System.out.println(""+data);
}
} catch (IOException e) {
// Error
}
}
If file contains:
Add label abc to xyz
Add instance cdd to pqr
I want to read each word from file and print it to a new line, e.g.
Add
label
abc
...
And afterwards, I want to extract the index of a specific string, for instance get the index of abc.
Can anyone please help me?
It sounds like you want to be able to do two things:
Print all words inside the file
Search the index of a specific word
In that case, I would suggest scanning all lines, splitting by any whitespace character (space, tab, etc.) and storing in a collection so you can later on search for it. Not the question is - can you have repeats and in that case which index would you like to print? The first? The last? All of them?
Assuming words are unique, you can simply do:
public static void main(String[] args) throws Exception {
File file = new File("/Users/OntologyFile.txt");
ArrayList<String> words = new ArrayList<String>();
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(
fstream));
String data = null;
while ((data = infile.readLine()) != null) {
for (String word : data.split("\\s+") {
words.add(word);
System.out.println(word);
}
}
} catch (IOException e) {
// Error
}
// search for the index of abc:
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals("abc")) {
System.out.println("abc index is " + i);
break;
}
}
}
If you don't break, it'll print every index of abc (if words are not unique). You could of course optimize it more if the set of words is very large, but for a small amount of data, this should suffice.
Of course, if you know in advance which words' indices you'd like to print, you could forego the extra data structure (the ArrayList) and simply print that as you scan the file, unless you want the printings (of words and specific indices) to be separate in output.
Split the String received for any whitespace with the regex \\s+ and print out the resultant data with a for loop.
public static void main(String[] args) { // Don't make main throw an exception
File file = new File("/Users/OntologyFile.txt");
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(fstream));
String data;
while ((data = infile.readLine()) != null) {
String[] words = data.split("\\s+"); // Split on whitespace
for (String word : words) { // Iterate through info
System.out.println(word); // Print it
}
}
} catch (IOException e) {
// Probably best to actually have this on there
System.err.println("Error found.");
e.printStackTrace();
}
}
Just add a for-each loop before printing the output :-
while ((data = infile.readLine()) != null) { // use if for reading just 1 line
for(String temp : data.split(" "))
System.out.println(temp); // no need to concatenate the empty string.
}
This will automatically print the individual strings, obtained from each String line read from the file, in a new line.
And afterwards, I want to extract the index of a specific string, for
instance get the index of abc.
I don't know what index are you actually talking about. But, if you want to take the index from the individual lines being read, then add a temporary variable with count initialised to 0.
Increment it till d equals abc here. Like,
int count = 0;
for(String temp : data.split(" ")){
count++;
if("abc".equals(temp))
System.out.println("Index of abc is : "+count);
System.out.println(temp);
}
Use Split() Function available in Class String.. You may manipulate according to your need.
or
use length keyword to iterate throughout the complete line
and if any non- alphabet character get the substring()and write it to the new line.
List<String> words = new ArrayList<String>();
while ((data = infile.readLine()) != null) {
for(String d : data.split(" ")) {
System.out.println(""+d);
}
words.addAll(Arrays.asList(data));
}
//words List will hold all the words. Do words.indexOf("abc") to get index
if(words.indexOf("abc") < 0) {
System.out.println("word not present");
} else {
System.out.println("word present at index " + words.indexOf("abc"))
}
I'm writing a java program that I'm running on the CMD line that copies several .txt files into one. For example I have three .txt files that I created. Chapter1.txt, chapter2.txt Chapter3.txt. All the contents of these files needs to be copied to book.txt. I ran the code and it ran fine until I entered the command.
java CatFiles chapter1.txt chapter2.txt chapter3.txt book.txt
The book.txt file is created but only the contents of one file are copied and I get this error code
java.land.illeglStateException: Scanner
at java.util.Scanner.ensureOpen(unknown Source)
at java.util.Scanner.findWithinHorizon(unknown Source)
at java.util.Scanner.hasNextLine(unknown Source)
at CatFiles.main(CatFiles.java)
Here's my code
public class CatFiles {
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.out.println("Usage: CatFiles sourcefile1 sourcefile2 . . . targetfile");
return;
}
String target = args[args.length - 1];
FileReader reader = null;
PrintWriter out = new PrintWriter(target);
for (int i = 0; i < args.length - 1; i++) {
String source = args[i];
reader = new FileReader(source);
}
Scanner in = new Scanner(reader);
while ( in .hasNextLine()) {
try {
String line = in .nextLine();
out.println(line);
} finally { in .close();
out.close();
}
}
}
}
Use this (note: checks about arguments are left as an exercise):
public static void main(final String... args)
{
final List<String> list = new ArrayList<>();
Collections.addAll(list, args);
final Path dstFile = Paths.get(list.remove(list.size() - 1));
try (
final OutputStream out = Files.newOutputStream(dstFile);
) {
for (final String s: list)
Files.copy(Paths.get(s), out);
}
}
You should put the while loop inside of the try block and not the contrary. Otherwise you're closing the Scanner at the first loop and you can not use it anymore. Close your Scanner once you're never using it again.
I honestly think correct indentation would have helped here.
JavaDoc
Throws: NoSuchElementException if no line was found
java.lang.IllegalStateException if this scanner is closed
Solution
Scanner in = new Scanner(reader);
try{
while (in.hasNextLine()) {
String line = in.nextLine();
out.println(line);
}
} finally {
in.close();
out.close();
}
Idiomatic Solution using Guava:
This includes basic error checking on valid number of arguments. This does not do robust idiomatic exception handling for brevity and scope control.
This solution also uses Immutable data throughout making it immune to logic errors because of side effects and state mutation.
Q33846584.java
Import statements are available in the link above.
public class Q33846584
{
public static void main(final String[] args) throws Exception
{
checkArgument(args.length > 2, "You must supply at least 3 file paths as arguments dest, src, src, ...");
final List<Path> paths = Lists.transform(Arrays.asList(args), new Function<String, Path>()
{
#Nullable #Override public Path apply(#Nullable String input)
{
return Paths.get(checkNotNull(input));
}
});
final Path destination = paths.get(0);
try (final OutputStream fos = new FileOutputStream(destination.toFile()))
{
for (final Path p : paths.subList(1, paths.size()))
{
if (p.toFile().exists())
{
System.out.format("Reading %s and writing to %s", p.toAbsolutePath(), destination.toAbsolutePath());
final FileInputStream fis = new FileInputStream(p.toFile());
ByteStreams.copy(fis, fos);
System.out.println();
}
else
{
System.err.format("%s does not exist skipping!", p.toAbsolutePath());
System.err.println();
}
}
}
}
}
Without Guava:
You would have to implement the transformation of the String[] yourself in a imperative loop which is straightforward.
You would have to implement copying the InputStream to the OutputStream which is well documented on the internet in general but is basically boilerplate code. You will end up with a possibly buggy or inefficient version of what Guava does. It would only be useful as a learning exercise at best.
Both of these activities are easy to find on Stackoverflow and are left as exercises for the reader.
I'm tasked, by my professor, to write a program to read a .csv file (778 rows (including header row), 8 columns).
I need to:
1. Write a method to receive the name of the file as its argument and then print the number of lines in the file.
public void printNumberOfLinesInFile(String fileName)
Write a method to receive the name of the file as its argument and then print the number of private and non-private colleges.
public void printNumberOfPrivateNonPrivateCollegesInFile(String fileName)
Write a method to receive the name of the file as its argument and then print the private college name with largest out of state tuition.
public void printMostExpensivePrivateCollegeInFile(String fileName)
Write a method to receive the name of the file as its argument and then print the non-private college with largest out of state tuition.
public void printMostExpensiveNonPrivateCollegeInFile(String fileName)
Write a method to receive the name of the file as its argument and then print the number of applications and the number of applicants that are accepted for private and non-private colleges.
public void printNumberOfApplications(String fileName)
Write a method to receive the name of the file as its argument and then print following information for private and non-private colleges.
Average of expenses for books.
Average of expenses for room.
Average of personal expenses.
public void printAverageOfExpenses(String fileName)
Disclaimer: I do not want anyone to do my homework for me. I need to learn so I can apply my knowledge when I graduate and enter industry. I'm simply asking for a hint or a better way at writing the code.
My code thus far:
public class Week14
{
public String data;
public void printNumberOfLinesInFile(String inFile) throws IOException
{
int collegeCount = 0;
FileReader fileRead = new FileReader(inFile);
BufferedReader bufferRead = new BufferedReader(fileRead);
while(true)
{
String line = bufferRead.readLine();
if(line == null)
{
break;
}
collegeCount++;
//System.out.println(line);
}
System.out.println(collegeCount-1 + " Colleges total.");
}
public void printNumberOfPrivateNonPrivateCollegesInFile(String inFile) throws IOException
{
int privateCount = 0;
int nonprivateCount = 0;
int count = 0;
FileReader fileRead = new FileReader(inFile);
BufferedReader bufferRead = new BufferedReader(fileRead);
while((data = bufferRead.readLine())!= null)
{
String line = bufferRead.readLine();
String [] lineItems = line.split(",");
for(int i = 0; i < line.length(); i++)
{
if(lineItems[i].equals("Yes"))
{
privateCount++;
}
}
break;
}
System.out.println(privateCount+" private Colleges.");
System.out.println(nonprivateCount+ " non-private Colleges.");
}
public void printMostExpensivePrivateCollegeInFile(String inFile) throws FileNotFoundException, IOException
{
int mostExpensive = 0;
int currentExpensive = 0;
FileReader fileRead = new FileReader(inFile);
BufferedReader bufferRead = new BufferedReader(fileRead);
while((data = bufferRead.readLine())!= null)
{
String line = bufferRead.readLine();
if(line.equals("OutstateTuition"))
{
System.out.println(line);
}
else
{
System.out.println(line);
}
}
}
public void printMostExpensiveNonPrivateCollegeInFile(String fileName)
{
}
public void printNumberOfApplications(String fileName)
{
}
public void printAverageOfExpenses(String fileName)
{
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
File inFile = new File("College.csv");
FileReader fileReader = new FileReader(inFile);
BufferedReader buffReader = new BufferedReader(fileReader);
Week14 w1 = new Week14();
//w1.printNumberOfLinesInFile("College.csv");
w1.printNumberOfPrivateNonPrivateCollegesInFile("College.csv");
//^^^The above line goes into an infinite loop^^^
//w1.printMostExpensivePrivateCollegeInFile("College.csv");
}
}
The problem is, I'm stuck on trying to count the amount of private and nonprivate colleges. In my method, printNumberOfPrivateNonPrivateCollegesInFile (line 39), I'm running into an exception: java.lang.ArrayIndexOutOfBoundsException: 8
I've asked my professor how I can avoid this, I've looked online and the problem seems to lie with the iterator int 'i'. I'm trying to traverse the array, and 'i' is out of bounds. When I put a '1' in
if(lineItems[i].equals("Yes"))
for my privateCount, there is an output of 67 from privateCount, (I think it is counting the individual characters for some reason).
My question, what would be the most effective way to traverse the entire .csv file, and to access individual columns so I can count them and output them?
Any help would be greatly appreciated.
edit:
I have changed the while loop:
while(true)
{
String line = bufferRead.readLine();
String [] lineItems = line.split(",");
if(line == null)
{
break;
}
for (String lineItem : lineItems) {
privateCount++;
}
}
Now I can traverse the entire .csv file, but I'm receiving a java.lang.NullPointerException when I try and count.
edit 2:
I've redone my while loop again,
while(true)
{
String line = bufferRead.readLine();
String [] lineItems = line.split(",");
for (String lineItem : lineItems) {
if (lineItem.equals("Yes")) {
privateCount++;
}
}
System.out.println(privateCount);
}
I'm now counting the right value for privateCount, but there's a NullPointerException at :
String [] lineItems = line.split(",");
and the loop will not let me put my 'echo' outside of the while-loop without a 'break' statement.
With respect to actual industry-level code, and assuming that assignment did not specifically focus on actual CSV decoding, I would recommend finding and using a library to handle low-level decoding, such as OpenCSV, SuperCSV or CSV-module for Jackson.
This way your code can focus on more interesting part of finding specific values, and not on intricate details like possible escaping and/or quoting of contents.
If the focus is on CSV edge cases this is not the approach to use; but for real production code one hopefully rarely if ever writes the actual low-level decoding part, given the existence of multiple good libraries for the task.
if(lineItems != null && lineItems.length>0){
// do your loop
}
if (lineItem!= null && !lineItem.trim().equals("") && lineItem.equals("Yes")) {
privateCount++;
}
most likely will prevent your null issue
public void printNumberOfPrivateNonPrivateCollegesInFile(String inFile) throws IOException
{
int privateCount = 0;
int nonprivateCount = 0;
FileReader fileRead = new FileReader(inFile);
BufferedReader bufferRead = new BufferedReader(fileRead);
try
{
while(true)
{
String line = bufferRead.readLine();
String [] lineItems = line.split(",");
//System.out.println(Arrays.toString(lineItems));
for (String lineItem : lineItems)
{
if (lineItem!= null && !lineItem.trim().isEmpty() && lineItem.equals("No"))
{
nonprivateCount++;
}
if (lineItem!= null && !lineItem.trim().isEmpty() && lineItem.equals("Yes"))
{
privateCount++;
}
}
//System.out.println(privateCount);
}
}
catch(NullPointerException npe)
{
}
System.out.println(privateCount);
System.out.println(nonprivateCount);
}
Fixed it. I'm now just catching the exception so it isn't as annoying. Thanks all for the help.
I am trying to write a java program to parse relevant strings from a .txt file with a certain format.
I want to use the contents of the .txt file to initiate data for my classes. A sample file would look like this:
Movies
Lord of the Rings: 180
Fight Club: 120
...
Theaters
A:100
B:50
C:200
...
Shows
1,1,960
1,1,1080
1,1,1200
1,3,1020
1,3,1140
2,2,990
2,2,1210
...
Prices
Adult:10
Child:7
Senior:8
...
End
This is what I have so far (and it is returning an error when trying to read the above file to initialize my class.
public static void inititializeFromFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while((line = reader.readLine()) != null) {
if(line.equals("Movies")) {
while (!(line.equals("Theaters"))) {
String currentline = line;
String[] parts = currentline.split(":");
String part1 = parts[0];
String part2 = parts[1];
movies.add(new Movie(part1, part2));
}
}
// do basic string comparisons here
if(line.equals("...")) {
// do something
}
else if(line.contains(":")) {
// most likely of type A:100, B:50
}
else if(line.equals("End")) {
// do something
}
else {
// anything else
}
}
reader.close();
}
}
Here is a sample program that will read in the file for you, line by line, and has some scenarios to determine what type of line we are looking at. I was lazy and threw the IOExceptions that might be thrown at me in the code - you should never do this, instead modify the program to use a try catch.
import java.io.*;
public class tmp {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = br.readLine()) != null) {
// do basic string comparisons here
if(line.equals("...")) {
// do something
}
else if(line.contains(":")) {
// most likely of type A:100, B:50
}
else if(line.equals("End")) {
// do something
}
else {
// anything else
}
}
br.close();
}
}
I require searching a word in a text file and display the line number using java. If it appears more than once I need to show all the line numbers in the output. Can anyone help me please?
Read the text file using Java class LineNumberReader and call method getLineNumber to find the current line number.
http://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
Something like this might work:
public ArrayList<Integer> find(String word, File text) throws IOException {
LineNumberReader rdr = new LineNumberReader(new FileReader(text));
ArrayList<Integer> results = new ArrayList<Integer>();
try {
String line = rdr.readLine();
if (line.indexOf(word) >= 0) {
results.add(rdr.getLineNumber());
}
} finally {
rdr.close();
}
return results;
}
You can store this information manually. Whenever you are invoking readline() of your BufferedReader, if you're using such, you can also increment a counter by one. E.g.,
public int grepLineNumber(String file, String word) throws Exception {
BufferedReader buf = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file))));
String line;
int lineNumber = 0;
while ((line = buf.readLine()) != null) {
lineNumber++;
if (word.equals(line)) {
return lineNumber;
}
}
return -1;
}