A Java program on CodeEval had to accept a file path as an argument. I used a command line argument to do this, but I get an exception as below when I submitted my code on CodeEval. What are some potential solutions to this problem?
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at java.util.StringTokenizer.nextElement(StringTokenizer.java:407)
at Main.FileRead(Main.java:61)
at Main.main(Main.java:26)
Here's the boilerplate Java code that I use for my Codeeval code. The specific problem code generally goes in the processLine method. I don't use Scanner or StringTokenizer. I use the String split method to process the input.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main implements Runnable {
private String fileName;
public Main (String fileName) {
this.fileName = fileName;
}
#Override
public void run() {
try {
processFile();
} catch (IOException e) {
e.printStackTrace();
}
}
private void processFile() throws IOException {
BufferedReader br = new BufferedReader(
new FileReader(fileName));
String line = "";
while ((line = br.readLine()) != null) {
processLine(line);
}
br.close();
}
private void processLine(String line) {
System.out.println(line);
}
public static void main(String[] args) {
new Main(args[0]).run();
}
}
Firstly, Check the name of class.Class name should be 'Main'.
Second you have to give all the imports in CodeEval Editor which you are using in your program.
This happens if you don't check to see if there are any more tokens (by calling hasMoreTokens). If no more tokens exist and you call nextToken, you will get this exception. However, without seeing the rest of your code, there is no way to know what is actually happening.
Related
I'm new to java and I'm having a little problem with my code. There's no error and such, it just keeps saying process finished but no output was displayed. The filename is correct as I've checked.
import java.nio.file.;
import java.io.;
public class GuessingGame {
public GuessingGame() {
String filename = "C:\\Users\\angela\\Documents\\words.txt";
Path path = Paths.get(filename.toString());
try {
InputStream input = Files.newInputStream(path);
BufferedReader read = new BufferedReader(new InputStreamReader(input));
String word = null;
while((word = read.readLine()) !=null) {
System.out.println(word);
}
}
catch(IOException ex) {
}
}
public static void main (String[] args) {
new GuessingGame();
}
}
You are ignoring the exception and you don't close the file. Save some typing by using the built-in input.transferTo() for copying the file to System.out, and pass on the exception for the caller to handle by adding throws IOException to constructor and main.
Replace your try-catch block with this try-with-resources, which handles closing the file after use:
try (InputStream input = Files.newInputStream(path)) {
input.transferTo(System.out) ;
}
You managed to call the intended class, but you also needed to specify the specific function which you have declared in the function. Like so:
public static void main (String[] args) { GuessingGame gg = new GuessingGame; gg.GuessingGame(); }
I have a private method called from the main() method to which I am passing the input file path as an argument. My code-under-test is the main() method. Somewhere in the middle of the private method, the file is read and some operations performed.
How can I:
1. Pass the file path of String type ("src/test/resources/test.txt") as an argument. I am getting FileNotFoundException if I pass the file path.
2. How can I test an IOException that is handled in private method on not finding the file?
Adding my code snippets here:
Code under Test:
public class MyApp {
public static void main(String[] args) {
new MyApp().readFile(args);
}
private void readFile(String[] args) {
if (args != null) {
String file = args[0];
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
// More business logic here for processing that line
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Test for main:
#Test
void mainTest() {
String[] args = {"/test_input.txt"};
MyApp.main(args);
assertNotNull(<some_object_after_processing>);
}
To get file path you can use suitable way mentation in this link
There is no need to check any assertion for main method.
If the test case is completed successfully then it passed.
Thank you for raising your queries! First, you need to change your application code because you are reading a single file from the args[0] position then why you are going to read the strings array [File Array or collection of files].
1] Create 'resources' folder in your project:
Right-click on project and create a folder with name 'resources'.
2] Create 'test.txt' into the 'resources' folder.
3] Modified code:
package com.application;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MyApp {
public static void main(String[] args) {
new MyApp().readFile("resources/Test.txt");
}
private void readFile(String fileName) {
if (fileName != null) {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
// More business logic here for processing that line
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Here, You can pass a fileName directly to the method. I hope that it will help you to resolve your first query.
I'm just starting out in java and I'm trying to make a greedy algorithm. The first step is to read the file.txt with the jewel values and bag weight limit and such. unfortunately I am having trouble getting the program to run. I am using eclipse and when I click run I get the following error message "the selection cannot be launched, and there are no recent launches".
When I select the java greedy algorithm folder in the file tree and select run i get the following message "selection does not contain a main type". the work file and file.txt are saved in the same folder on my desktop but I wonder if the program isn't finding it. here's my code:
/** open and read a file, and return the lines in the file as a list of strings */
private List<String> readFile(file.txt)
{
List<String> records = new ArrayList<String>();
try
{
BufferedReader reader = new BufferedReader(new FileReader(file.txt));
String line;
while (( line = reader.readLine()) != null)
{
records.add(line);
}
reader.close():
return records;
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.", file.txt);
e.printStackTrace();
return null;
}
}
Thanks for the help.
You have to add a method named void main(String[] args).
This is the method that gets called when you start your program.
In this main method you can call your readFile method, like so:
public static void main(String[] args) {
readFile();
}
A java class should have a main method then only you can run that.
So, your class will be like this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String... args) {
//call readFile
List<String> someList = readFile(<pass filename here>);
//do something here with someList
}
/** open and read a file, and return the lines in the file as a list of strings */
private static List<String> readFile(String filename)
{
List<String> records = new ArrayList<>();
try
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while (( line = reader.readLine()) != null)
{
records.add(line);
}
reader.close();
return records;
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.",filename );
e.printStackTrace();
return null;
}
}
}
Note that, I marked readFile method as static which is because I am invoking it from main method without creating an instance of Test class. If you create an instance of Test class, and call readFile method on it, then you can remove static modifier.
You are missing the
public static void main(String args[])
{
...
}
There you can call your function.
I would like to know how to write all lines from the java output in a .txt file.
I've done some tests so far but I don't seem to be able to find the solution :/
Here is a small code, if you could show me with this one, it would be greatly appreciated :
The code shown below asks the user what to write in a .txt file but I want it to write all the printed lines in a .txt file without asking the user anything. Thank you
package test;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Test {
public static void main(String[] args)throws Exception {
System.out.println("Hello");
System.out.println("Hi");
System.out.println("Hola");
System.out.println("Bonjour");
System.out.println("Hallo");
System.out.println("Hej");
System.out.println("Alo");
System.out.println("Ciao");
writeOutput();
}
public static void writeOutput() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromInput = in.readLine();
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
out.println(lineFromInput);
out.close();
}
}
Use directly PrintStream to write the String values.
public static void main(String[] args)throws Exception {
PrintStream printStream = new PrintStream(new File("output.txt"));
// hook for closing the stream
Runtime.getRuntime().addShutdownHook(new Thread(printStream::close));
// writing
write(printStream,"Hello", "Hi", "Hola", "Bonjour", "Hallo", "Hej",
"Alo","Ciao");
// writing again
write(printStream, "A new String", "And again another one...");
}
public static void write(PrintStream printStream, String... values) throws Exception {
try{
for (String value : values){
printStream.println(value);
}
printStream.flush();
}
catch (Exception e){
// handling exception
}
}
}
java test.Test > somefile.txt
Java is not my main programming language so I might be asking the obvious.
But is there a simple file-handling library in Java, like in python?
For example I just want to say:
File f = Open('file.txt', 'w')
for(String line:f){
//do something with the line from file
}
Thanks!
UPDATE: Well, the stackoverflow auto-accepted a weird answer. It has to do with bounty that I placed - so if you want to see other answers, just scroll down!
I was thinking something more along the lines of:
File f = File.open("C:/Users/File.txt");
for(String s : f){
System.out.println(s);
}
Here is my source code for it:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
public abstract class File implements Iterable<String>{
public final static String READ = "r";
public final static String WRITE = "w";
public static File open(String filepath) throws IOException{
return open(filepath, READ);
}
public static File open(String filepath, String mode) throws IOException{
if(mode == READ){
return new ReadableFile(filepath);
}else if(mode == WRITE){
return new WritableFile(filepath);
}
throw new IllegalArgumentException("Invalid File Write mode '" + mode + "'");
}
//common methods
public abstract void close() throws IOException;
// writer specific
public abstract void write(String s) throws IOException;
}
class WritableFile extends File{
String filepath;
Writer writer;
public WritableFile(String filepath){
this.filepath = filepath;
}
private Writer writer() throws IOException{
if(this.writer == null){
writer = new BufferedWriter(new FileWriter(this.filepath));
}
return writer;
}
public void write(String chars) throws IOException{
writer().write(chars);
}
public void close() throws IOException{
writer().close();
}
#Override
public Iterator<String> iterator() {
return null;
}
}
class ReadableFile extends File implements Iterator<String>{
private BufferedReader reader;
private String line;
private String read_ahead;
public ReadableFile(String filepath) throws IOException{
this.reader = new BufferedReader(new FileReader(filepath));
this.read_ahead = this.reader.readLine();
}
private Reader reader() throws IOException{
if(reader == null){
reader = new BufferedReader(new FileReader(filepath));
}
return reader;
}
#Override
public Iterator<String> iterator() {
return this;
}
#Override
public void close() throws IOException {
reader().close();
}
#Override
public void write(String s) throws IOException {
throw new IOException("Cannot write to a read-only file.");
}
#Override
public boolean hasNext() {
return this.read_ahead != null;
}
#Override
public String next() {
if(read_ahead == null)
line = null;
else
line = new String(this.read_ahead);
try {
read_ahead = this.reader.readLine();
} catch (IOException e) {
read_ahead = null;
reader.close()
}
return line;
}
#Override
public void remove() {
// do nothing
}
}
and here is the unit-test for it:
import java.io.IOException;
import org.junit.Test;
public class FileTest {
#Test
public void testFile(){
File f;
try {
f = File.open("File.java");
for(String s : f){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Test
public void testReadAndWriteFile(){
File from;
File to;
try {
from = File.open("File.java");
to = File.open("Out.txt", "w");
for(String s : from){
to.write(s + System.getProperty("line.separator"));
}
to.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Reading a file line by line in Java:
BufferedReader in = new BufferedReader(new FileReader("myfile.txt"));
String line;
while ((line = in.readLine()) != null) {
// Do something with this line
System.out.println(line);
}
in.close();
Most of the classes for I/O are in the package java.io. See the API documentation for that package. Have a look at Sun's Java I/O tutorial for more detailed information.
addition: The example above will use the default character encoding of your system to read the text file. If you want to explicitly specify the character encoding, for example UTF-8, change the first line to this:
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("myfile.txt"), "UTF-8"));
If you already have dependencies to Apache commons lang and commons io this could be an alternative:
String[] lines = StringUtils.split(FileUtils.readFileToString(new File("myfile.txt")), '\n');
for(String line: lines){
//do something with the line from file
}
(I would prefer Jesper's answer)
If you want to iterate through a file by strings, a class you might find useful is the Scanner class.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("myFile.txt")));
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
The API is pretty useful: http://java.sun.com/javase/7/docs/api/java/util/Scanner.html
You can also parse the file using regular expressions.
I never get tired of pimping Google's guava-libraries, which takes a lot of the pain out of... well, most things in Java.
How about:
for (String line : Files.readLines(new File("file.txt"), Charsets.UTF_8)) {
// Do something
}
In the case where you have a large file, and want a line-by-line callback (rather than reading the whole thing into memory) you can use a LineProcessor, which adds a bit of boilerplate (due to the lack of closures... sigh) but still shields you from dealing with the reading itself, and all associated Exceptions:
int matching = Files.readLines(new File("file.txt"), Charsets.UTF_8, new LineProcessor<Integer>(){
int count;
Integer getResult() {return count;}
boolean processLine(String line) {
if (line.equals("foo")
count++;
return true;
}
});
If you don't actually want a result back out of the processor, and you never abort early (the reason for the boolean return from processLine) you could then do something like:
class SimpleLineCallback extends LineProcessor<Void> {
Void getResult{ return null; }
boolean processLine(String line) {
doProcess(line);
return true;
}
abstract void doProcess(String line);
}
and then your code might be:
Files.readLines(new File("file.txt"), Charsets.UTF_8, new SimpleLineProcessor(){
void doProcess(String line) {
if (line.equals("foo");
throw new FooException("File shouldn't contain 'foo'!");
}
});
which is correspondingly cleaner.
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("scan.txt"));
try {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
scanner.close();
}
}
Some caveats:
That uses the default system encoding, but you should specify the file encoding
Scanner swallows I/O exceptions, so you may want to check ioException() at the end for proper error handling
Simple example using Files.readLines() from guava-io with a LineProcessor callback:
import java.io.File;
import java.io.IOException;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class GuavaIoDemo {
public static void main(String[] args) throws Exception {
int result = Files.readLines(new File("/home/pascal/.vimrc"), //
Charsets.UTF_8, //
new LineProcessor<Integer>() {
int counter;
public Integer getResult() {
return counter;
}
public boolean processLine(String line) throws IOException {
counter++;
System.out.println(line);
return true;
}
});
}
}
You could use jython which lets you run Python syntax in Java.
Nice example here: Line by line iteration
Try looking at groovy!
Its a superset of Java that runs in hte JVM. Most valid Java code is also valid Groovy so you have access any of the million java APIs directly.
In addition it has many of the higher level contructs familiar to Pythonists, plus
a number of extensions to take the pain out of Maps, Lists, sql, xml and you guessed it -- file IO.