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(); }
Related
I am trying to write strings to a file but all the strings are being written to the file once the script is terminated.
To make my problem clear, in the below code I want to write a single string to my files per second and my file should be updated each second. Please help I am new to java.
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException {
String[] list = "Should write each word in each iteration".split("\\s");
for(String word:list){
Writer obj = new Writer();
obj.func(word);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
}
class Writer{
public void func(String word) throws IOException{
FileWriter writer = new FileWriter("file" , true);
writer.write(word);
writer.close();
}
}
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 am trying to work with file stream and i have a problem.
This is my code :
import java.io.*;
import java.util.*;
public class FileIO {
public static void main(String[] args) {
FileOperations myFile = new FileOperations("C:\\My_Programs\\eclipse\\MyJavaFiles\\myFile.txt");
}
private static class FileOperations {
String fileName;
// constructor without argument
FileOperations() {
fileName = "default";
}
/*
* constructor with argument
* argument is assinged into fileName
* fileName is used to open stream for input and output
*/
FileOperations(String argfileName) {
fileName = argfileName;
try {
// open ouput stream
PrintWriter fileOutput = new PrintWriter(new FileOutputStream(fileName));
// open input stream
BufferedReader fileInput = new BufferedReader(new FileReader(fileName));
} catch (IOException v) {
System.out.println(v);
}
}
}
}
My problem is, that if i implement whole FileOperations class in main method, it works fine and i can use fileOutput and fileInput without any problem.
But i wanted to implement those streams in other method and this is where i got stucked.
Why can't i use something like String fileLine = myFile.fileInput.readLine(); in main method? For me, it looks like those streams are not even opened despite they should be.
I am aware that i didn't close fileInput nor fileOuptu, i would close it after working with file.
Thank you for all advices and explanations!
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.