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.
Related
This question already has an answer here:
Unreported exception java
(1 answer)
Closed 2 years ago.
I have some trouble finding the file in a java program in mac system.
import java.io.File;
import java.util.Scanner;
import java.net.MalformedURLException;
import java.net.URL;
public class Data{
public static void main(String[] args){
File file = new File("/Users/project/test.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
In the same directory, when I typed this command Javac Data.java, it would give this error
I have read multiple similar posts on StackOverflow, but unfortunately, I couldn't find a solution.
Data.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown Scanner sc = new Scanner(file);
^
1 error
I have tried setting the file path like:
"./test.txt"
"test.txt"
"/text.txt"
But still, the same error would occur.
I don't know if this is relevant, but I can only run the java command in the terminal in the ~ directory, and all the above java files are in the ~ directory too.
Does anyone have any suggestions?
Your code is not throwing an exception. Your error message does not mean that the FileNotFoundException is thrown.
You have a compile time error.
Whenever you open a file, it must be like this:
try {
File file = new File("/Users/tianrongzhen/project/test.txt");
} catch (Exception e) {
// handle exception here
}
Or like this:
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/Users/tianrongzhen/project/test.txt");
// rest of your code
}
There are 2 kinds of exceptions: Checked and Unchecked.
A Checked exception can be considered one that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch or throw it.
For example, opening a file. It has a chance to fail, and the compiler knows this, so you're forced to catch or throw the possible IOException or FileNotFoundException.
There is a huge difference between the two ways to handle exceptions above.
First one catches and handles Exception internally, so the caller doesn't have to do any exception handling.
Second one throws Exception, so the caller needs to handle the Exception.
Based on the question you have asked here, I would recommend you to read up on the basics on exception handling. Here is one resource, but feel free to explore.
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
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
A related question is this one: Where is the specification that defines this behavior for InputStreamReader?, but I'm not sure if it answers mine...
Please note, I'm just experimenting with the language.
I have this code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Capitalize {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(
System.in))) {
char c;
do {
c = Character.toUpperCase((char) br.read());
System.out.print(c);
} while (c != (char) -1);
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
Using ubuntu linux, I was expecting the output to be like this:
fFoOoO bBaArR
but instead, it's like this:
foo bar (line feed)
FOO BAR (waits for more characters or Ctrl + D)
Right now I'm not sure about what is the behavior in windows, probably it's different, but still, this confuses me a bit. Reading the documentation for the read method, I see it will only return -1 if the end of stream is reached. I kind of understand how that would work for reading a file, but how about, in this case, the console? Why does it have to wait until the Ctrl + D is typed? Is there any way to get to the end of the stream without having to type Ctrl + D? Is there a way to achieve what I was expecting?
Thanks in advance
As EJP comments, this is nothing to do with InputStream / BufferedReader. What you are seeing is the behaviour of the Linux "tty" input drivers and a typical console command.
What you are seeing is normal "line editing" or "line buffering". The input is only made available for Java to read (via the stdin file descriptor) when you press the <Enter> key. The output you are seeing prior to that is the character echoing from the "tty" drivers. (And notice that if you enter <Backspace> or whatever ... the characters get erased. When you type <Enter>, Java doesn't see the backspaces, etc. They have been edited out.)
Input via the java.io.Console class behaves the same way.
This is the same on Windows: the behaviour is portable. (This is a good thing ...)
If you want your Java application to see the characters as they are typed, when they are typed, you will need to use 3rd-party libraries (or native code) to implement this. (In Linux, it entails switching the tty driver into "raw" mode ... and this functionality is non-portable, and not supported by standard Java SE.)