I wrote this simple program to try to read information from a txt file in my computer's D drive`
package readDisk;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class ReadDisk
{
public static void main(String[] args) {
Scanner input = new Scanner(Path.of("D:\\test.txt"), StandardCharsets.UTF_8);
String TestText = input.nextLine();
System.out.println(TestText);
}
}
I am getting an error message upon compilation which goes
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method of(String) is undefined for the type Path
at readDisk.ReadDisk.main(ReadDisk.java:9)
I am following a sample program found in the 11th Edition of Core Java Volume 1 and I've looked all over, trying to find where I've gone wrong to no avail. Any help will be appreciated.
As opposed to what some commenters say, the method you're trying to use does actually exist. The method in question takes a required first argument, and then a variable number of arguments, effectuated by the varargs construct, which means zero or more arguments.
But it is only available from Java 11 onwards. You need to check your Java version.
An alternative would be that you use scanner with another argument:
new Scanner(new File(D:/test.txt), StandardCharsets.UTF_8); or
new Scanner(Paths.get(D:/test.txt), StandardCharsets.UTF_8)
The constructors throw a FileNotFoundException and an IOException respectively. Make sure you either handle it or propagate it to the caller.
Note: A quick local test has shown me that this actually works for me. So if your code still throws a FileNoteFoundException, my guess is there is something otherwise wrong with the file or filename.
Try initializing your Scanner as below, you don't need Path for this :
Scanner input = new Scanner(new File("D:\\test.txt") , StandardCharsets.UTF_8);
The Path.of() method, added in JDK 11, requires a URI as parameter, not a String. For example,
Scanner input = new Scanner(Path.of(new URI("file:///D:/test.txt")), StandardCharsets.UTF_8);
Or you can simply use new Scanner(File), as other answer said.
Your code is fine Path::of method can take only one argument since the second one is vararg. Just make sure you are using java 11
Related
I'm joining Hackerrank for the first time. Just for some practise purposes.
Then, I found this line
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
and pretty confused about what's the correct replacement for the "OUTPUT_PATH". Because the code was copied into my IDE (Eclipse) I read the documentation but none of the reserved values suited. They all throwed NPE.
What's the correct parameter value of the System.getenv("..") in my case?
In case you need the full code:
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.JOptionPane;
public class Solution {
/*
* Complete the simpleArraySum function below.
*/
static int simpleArraySum(int[] ar) {
return 2;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
//name − This is the name of the environment variable.
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = Integer.parseInt(scanner.nextLine().trim());
int[] ar = new int[arCount];
String[] arItems = scanner.nextLine().split(" ");
for (int arItr = 0; arItr < arCount; arItr++) {
int arItem = Integer.parseInt(arItems[arItr].trim());
ar[arItr] = arItem;
}
int result = simpleArraySum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
}
}
I know that this question is bit old, but maybe somebody will have benefits from this answer...
This line:
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
reads the environment variable defined in Hackerrank runtime/testing environment to determine the place where results will be stored for further analysis.
In order to use exactly the same code, you have to create this variable on your system and use it, or change to store results on different place (as it is already explained in previous answers and comments).
But, ...
Since this is used for a Hackerrank solving, I think it is better to have all outputs redirected to system.out instead of file, because it is far more useful to see results at runtime (or debug) in the IDE console rather than places it in a file.
So, this line is better to change on this way:
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));
which will stream your BufferedReader to System.out.
In that case You will have same output as it is on Hackerrank test cases, but in your IDE console instead in file.
That "OUTPUT_PATH" is an environmental variables. You have to declare that variable in your operating system to use it. Generally website like hackerrank do it because learning the path of there system is not good for security I guess. You can test your code in IDE but the environmental variables will be not there you need to declare. I hope it helped you for your confusion.
The question is already answered with a proper explanation. I am just adding the steps that you can simply use if your IDE is IntelliJ IDEA.
Step 1: When you run any main class in IDE, you can see there will be an option called Edit Configurations like this
Step 2: Click on Edit Configurations. On click, you will see this.
Step 3: Click on 3 dots that are circled in the above image. On click, you will see this.
Step 4: Click on + symbol (as circled in the image) and add these environment variables as shown in the image. Once done click on the Apply button and you should be good to run your program.
This would be no different than the Hackerrank environment. Hope this helps.
As I said in the comments, you're not supposed to replace it. That's an environment variable in the shell that is used to run your solution.
Seeing as the value of the variable is passed to FileWriter, this means that it represents the name of a file.
You can replicate it in a terminal by running your program with the command:
env OUTPUT_PATH=/path/to/some/file java Solution
This will start a new shell which contains a variable called OUTPUT_PATH pointing to a file called /path/to/some/file and when the program starts, the file name will be used
In Eclipse you can set Environment variable as shown below:
Right click on Java file. And, you will get eclipse context menu as shown below. Click on Run configuration.
In newly opened window. Click on Environment Tab. Here you can add Environment variable and value of your choice as shown in image below. Close this window.
Right click again on java code, click on Run, then Run as Java Application.
I'm trying to write a parser to a file called "x". I want to use scanner. I tryied to follow actions from a tutorial: https://www.youtube.com/watch?v=3RNYUKxAgmw.
package q;
import java.io.File;
import java.util.Scanner;
public class Parser {
public static void main(String [] args) {
Scanner x = new Scanner(new File("/home/x/eclipse-workspace/q/src/q/x.txt"));
String s=x.nextLine();
System.out.print(s);
}
}
The file that I want to open is called "x", its text file. We can see it in Package Explorer on left side. I clicked right on its properties. There is visible file locatization.
There appears FileNotFoundException as on the picture. I doesn't understand why this file cannot be opened.
[update] But I'm not sure if this is what
There appears FileNotFoundException as on the picture. I doesn't
understand why this file cannot be opened.
That's not what's happening. The error is in compilation time (the program has not executed, it doesn't know if the file -will- exist). The compiler is telling you "this method/constructor, according to its declaration, can throw an Exception (in this case: a FileNotFoundException ) at run time; you have not told me what to do in that case".
You really need to read about how Exceptions are treated in Java.
For a quick remedy, add a throws Exception to your main declaration. (Bear in mind: that is an awful thing to do if you don't really understand what are you doing)
Before I start, I'd like to say that I've spent 4 hours today, 6 hours yesterday and 3 hours before that researching this issue. I've read every post I can find, followed every instruction to the letter, restarted my project, reinstalled my IDE (Netbeans) and even fresh installed my OS, and I haven't found a single piece of helpful advice, so I figured I needed to ask for help.
AND YES, I HAVE PUT THE FILE IN THE RIGHT LOCATION
... As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents. I've checked and changed and defaulted the root directory many times. PLEASE don't tell me to just use an exception handler. The file the program reads in is guaranteed to exist and contain something.
So here's my question:
I'm trying to input and read from a file, however, the result is always that the file can't be found. Here's an example of my code (and it really is down to this atm):
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
FileReader inputFile = new FileReader(args[0]);
}
}
Here are two of the errors I get (I also get Filenotfound errors, but I don't think I need to add that):
Exception in thread "main" java.lang.RuntimeException: Uncompilable source
code - unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown
at project2.Project2.main(Project2.java:14)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 1 second)
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at project2.Project2.main(Project2.java:24)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 0 seconds)
That's it. The file name comes from the arguments, and I have tried every possible variation of the name. I have tried naming the file outside of the arguments, as just the file name itself and also with an explicit file path.
Using a scanner won't let me read anything in. FileReader won't even run.
The text file has no special formatting or characters, and I've used the one I was supplied with and multiple that I hand typed just in case there was an issue with the one I was given. I have also made sure that ".txt" is never read or used twice (I keep my extensions on, anyway).
I have checked attributes and permissions of all files and the Netbeans program itself. I've also made sure that the text files were included in the project build.
I am not using any additional code right now, as I can't do anything until I'm sure that I can read in a file, and then output one as well. I also know that the text files aren't corrupt because I can read them in Python just fine, however, I have to use Java and I have to use Netbeans.
This is a new problem for me, I've always been able to read in files fine, and I've exhausted my options. I really need some help if anyone has any ideas.
The first exception (java.lang.RuntimeException: Uncompilable source
code) is thrown because the code that you have shown us is not valid java source code.
new FileReader(args[0]) is declared as throwing FileNotFoundException and according to the rules of the java language you either have to catch this exception or declare your main method as throwing this exception.
One way to fix this problem is to write your main method like this:
public static void main(String[] args) throws FileNotFoundException {
FileReader inputFile = new FileReader(args[0]);
}
It seems that you have solved this issue because the second exception (java.util.NoSuchElementException: No line found) is thrown by the Scanner.nextLine() method if you try to read past the end of the file.
Since you have not shown any code using the Scanner class it's hard to tell where to problem is in this case.
As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents.
Don't do that. You are creating a mess with files that will be hard to cleanup. If you want to know which file your program is reading then adding the following simple line tells you the exact path and filename:
System.out.println(new File(args[0]).getAbsolutePath());
Have you ever tried with a simple, minimal example like this:
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
System.out.println(new File(args[0]).getAbsolutePath());
FileReader inputFile = new FileReader(args[0]);
try (Scanner s = new Scanner(inputFile)) {
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
}
}
}
It should print out the name of your file with the complete path and then the contents of the file line by line.
I don't think Java is messing around with you a not found file is a not found file, please elaborate more in this issue by screens of files and directories you are working on.
I would like you to consider take a look at the following:
FileReader
Path of projects on Netbeans
I hope this helps may the code be with you.
This reads a file with no problem. I'll assume you're running JDK 8.
/**
* Read a file example
* User: mduffy
* Date: 4/21/2017
* Time: 7:48 AM
* #link http://stackoverflow.com/questions/43529600/java-nothing-will-read-in-this-file
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Project2 {
public static void main(String[] args) {
if (args.length > 0) {
BufferedReader reader = null;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))) {
bufferedReader.lines().forEach(System.out::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Usage: Project2 <file>");
}
}
}
Here's the input file I used:
line1
line2
hello, michael
line 4
Here's the output I got:
java Project2 .\src\main\resources\test.txt
line1
line2
hello, michael
line 4
Process finished with exit code 0
This is my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class temp {
public static void main(String[] args) throws FileNotFoundException {
BufferedReader a = new BufferedReader(new FileReader("a"));
Scanner scanner = new Scanner(a).useDelimiter(",");
scanner.close();
}
}
I get a warning at new Scanner(a) that says (I'm compiling with jdk1.7.0_05.):
Resource leak: '<unassigned Closeable value>' is never closed.
Am I doing something wrong, or is this just a false warning?
If you split the code like this, will the warning go away?
Scanner scanner = new Scanner(a);
scanner.useDelimiter(",");
scanner.close();
Yes, your code has a potential (but not real) memory leak. You assign the return value of useDelimiter(a) to the local variable scanner, but the constructor result is thrown away. That is why you get the warning.
In practice, the return value of useDelimiter(a) is exactly the same object as the one returned from the constructor call, so your code closes the resource just fine. But this is something the compiler/code analysis tool cannot detect as it would have to know the useDelimiters implementation for that.
And a really good code analysis tool should have shown you an additional warning, because you are closing a resource which has not been opened in this method (the return value of useDelimiter). If you had those 2 messages together, the symptoms might have been more clear to you.
Have you try :
Scanner scanner = new Scanner(new BufferedReader(new FileReader("a"))).useDelimiter(",");
If it does not work you have to add a.close();
What is giving you this warning? Presumably it warns because the allocation/closing isn't done in a try/finally block, which generally is a bad idea (in this specific case not a problem though because the only thing that can throw an error is the new FileReader and if it throws no resource was actually allocated - but that can change with a single method call..)
Closing a scanner closes the underlying stream (to be exact anything that implements itself Closeable (yes BufferedReader does) so the code is fine apart from that.
I am trying to test an ANTLR grammar with such a standard test rig
import org.antlr.runtime.*;
class Main {
public static void main(String[] args) throws Exception {
SampleLexer lexer = new SampleLexer(new ANTLRStringStream(args[0]));
SampleParser parser = new SampleParser(new CommonTokenStream(lexer));
parser.program();
}
}
I have a test file called mytest00. Now I want to use this file as input. I suppose I am doing a stardard IO redirection here.
bash-3.2$ java Main < mytest00
But it gives me such an error message. What is the problem please? Thanks.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(SampleTest.java:5)
You're trying to use args[0] but you haven't actually passed in any command line arguments - you've just redirected a file into the standard input of the process. So the array has no elements, and you're getting an exception because you're trying to get the first element of that empty array.
It's not really clear that you actually want ANTLRStringStream. I suspect you want ANTLRInputStream wrapping System.in if args.length == 0, and ANTLRFileStream(args[0]) otherwise.
when you use < as parameter , OS treats it as input redirection . so it will check for it and it won't pass argument the java main()
What the exception means and how to deal with exceptions generally
at Main.main(SampleTest.java:5)
The problem appears in 5 line of your code, which is:
SampleLexer lexer = new SampleLexer(new ANTLRStringStream(args[0]));
and the Exception is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
which means you're trying to retrieve 0-element from your array args, the array has been accessed with an illegal index because the array is empty (size=0)
Example solution
You want to use this constructor:
public ANTLRStringStream(String str)
To do this you can:
read standard input to some String
pass this String to ANTLRStringStream constructor