Java: Nothing will read in this file - java

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

Related

Having trouble reading information from a file using Scanner class

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

Opening a file FileNotFoundException with scanner in Java, Eclipse, Ubuntu

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)

Make a cloned jar file of itself

hey guys i just make some changes to the previous one ....
that is
import java.io.*;
import java.nio.*;
public class Test1234{
public static void main(String args[]){
File inputF = new File(Test1234.class.getProtectionDomain().getCodeSource().getLocation().getFile());
File outputF = new File("D:\\test.class");
FilePermission adb = new FilePermission(inputF.getPath(),"write,read,execute");
Files.copy(inputF.toPath(),outputF.toPath(),REPLACE_EXISTING);
}
}
for simplicity the inputF points to the class file itself. And it compiles perfect. but when i found the file test.class it only is an empty folder.
so please guys help me !!! I'm stuck with this problem.
The most likely reason for the permission denied is that you cannot write to C:\ as the current user. Chose a folder you can write to or run as administrator.
Since you are running a plain main method there is very probably no SecurityManager, plus you would get a SecurityException if that was the problem. Also, it does not matter whether you read the current code source, only on Windows you cannot delete or write to it since this would be locked by the OS.
If that is not the problem, you need to verify Test1234.class.getProtectionDomain().getCodeSource().getLocation().getPath() points to what you actually want to copy. A stack trace would help in that case.
i just found out the solution by building my class file to jar file. then when i run it, it created a cloned jar file named test.jar. by when i just say this one you must change the outputF path to "d:\test.jar". :)

Creating an empty file in a directory

I am a new java student currently working on File I/O. My professor has asked us to create a very simple "DC universe" game using interfaces and classes and has asked us in the current lab I am working on, to create an instance of an object and then save the file to a directory in our C drive. My problem, is that even after all my constant 2 hours of digging through past topics I still cannot find a proper explanation as to how I create a directory and THEN create a file and write to a file in that directory because it appears whenever I run my code to not be able to do both tasks simultaneously. The code below also contains an error at the "Print Writer" line and asks to add a throw clause for "file not found exception"
Any and all help is vastly appreciated
package runtime;
import java.io.*;
import java.util.*;
import model.hero.*;
public class Gameplay {
public static void main(String[] args) {
File x = new File("C://prog24178//dcheroes.dat");
if(!x.exists()){
x.mkdir();
}
PrintWriter output = new PrintWriter(x);
// 1. Create a save file called dcheroes.dat in {$root}\prog24178
// 2. Create a hero
// 3. Save hero to file
}
}
Two errors I see:
x.mkdir() will try to create C:\prog24178\dcheroes.dat as a directory. Use x.getParent().mkdir() to create C:\prog24178.
the PrintWriter error is Java complaining about you not catching a potential error. Your code is fine, it's just Java being demanding. Surround your code with a try { ... } catch (FileNotFoundException ex) { ... } block. Every function call that could potentionally throw an Exception needs to have that exception caught, or the containing function needs to be marked to also be a potential source of the exception (and you can't do the latter on main).

How to open the temporary directory in Java?

Dear community members,
I have a small problem with the following code. I think it should open the explorer in the C:\Users\Me\AppData\Local\Temp\ directory. However that does not work, actually nothing happens. No errors.
I have used the following code:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
Desktop.getDesktop().open(File.createTempFile("abcd", ".temp").getParentFile());
} catch (IOException e) {
e.printStackTrace();
}
}
}
If I replace it with a normal file, like new File("C:\"), then it does work. Can someone explain to me why it does not work?
PS: guys I forgot to tell you I also tried it with some characters like "abcd", it still gives nothing and shows nothing!
Just use new File(System.getProperty("java.io.tmpdir")): that's the temp directory. No need for dirty tricks with the parent of a useless temporary file...
Looking at the Javadoc for the File class:
Parameters:
prefix - The prefix string to be used in generating the file's name; must be at least three characters long
So it appears that "" isn't a valid argument for the file prefix.
According to the docs for File.createTempFile(), if the prefix (first argument) contains fewer than three characters, an IllegalArgumentException will be thrown. You should see it in your console output.

Categories

Resources