javac error: Scanner: FileNotFoundException - java

I'm now writing a java class and want to read a txt file in, like this:
public class Myclass {
...
public static void main(String[] args) {
try{
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
int [] array = new int [1000];
int i = 0;
while(scanner.hasNextInt())array[i++] = scanner.nextInt();}
catch (FileNotFoundException exp) {
exp.printStackTrace();}
}
...
}
And for example, use it like java Myclass input.txt. However when I use javac to compile it in Linux, erros throws:
error: cannot find symbol
catch (FileNotFoundException exp) {
^
symbol: class FileNotFoundException
location: class Myclass
That's weird since name of input file hasn't even been passed in. I've tried File file = new File('input.txt'); and it also throws this error, so I don't know what's wrong (System.out.println(new File('input.txt').getAbsolutePath());will print out the correct and existed path).

You need to add correct imports at the begining of a class:
import java.io.FileNotFoundException;
public class Myclass {...

i think you have to compile your class using the following command
javac com/Trail.java
javac <package-name1>/<package-name2>/<classname.java>
then run the following command
java com.Trail test.txt
the you have to ensure test.txt place then it will works for you, let me recommand you the following answer of the question it helps me a lot to run your code here and here
for where you should put your file
note:
try to declare public static void main(String args[]) throws FileNotFoundException
please you have to be inside folder of file which you want to compile

It looks like you did not import the class FileNotFoundException.
Adding a import java.io.FileNotFoundException at the top of your file should resolve the issue.

Assuming all the imports are alright, the next most likely cause is the txt file is not there. You have to put your txt file at the same folder that there are folders like "src", "dist" and "build".

I've figured it out!
declare main like this:
public static void main(String args[]) throws FileNotFoundException{
...

Try to put the location of file that you want to read, something like this:
File file = new File("C:\\text.txt");
Full example:
public static void main(String[] args)
{
File file = new File("C:\\text.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}

Related

.getAbsolutePath() function works differently in eclipse and cmd

I have a program that scans a file.
import java.util.*;
import java.io.*;
public class testProgram {
private static Scanner scan;
private static File file;
private static String filePath;
private static String content;
public static void main(String[] args) throws InterruptedException{
filePath = "files\\text.txt";
file = new File(filePath);
file.getAbsoluteFile();
try {
scan = new Scanner(file);
while(scan.hasNextLine()) {
content = scan.nextLine();
System.out.println(content);
}
Thread.sleep(10000);
}
catch (FileNotFoundException e) {
System.out.println("file not found");
Thread.sleep(10000);
}
}
}
I tried to run this in eclipse and it works fine. The absolute path shows like this:
"D:\Programming\Java\Test Program\files\text.txt"
When I compiled it into batch file and run the program in cmd, the program doesn't work because the absolute path is now different:
"D:\Programming\Java\Test Program\src\files\text.txt"
This is what my batch file looks like:
echo off
cls
java testProgram
Although the java file (the one that works in Eclipse) and the batch file (that doesn't work) were in the same folder but the batch file acts differently in terms of file paths. I want them to work in eclipse or in cmd. Why does this happen and is it possible to resolve this? Sorry for the trouble, Beginner here :)

Why any file can be read with using java.security.SecurityManager in java?

I just want some files to be read and written in my Java program. So I use java.security.SecurityManager to manage this, but it seems unsatisfactory.
The Main.java file is below
import java.io.*;
import java.util.*;
public class Main {
static private final String INPUT = "in.txt";
public static void main(String args[]) throws Exception {
FileInputStream instream = null;
BufferedReader reader = new BufferedReader(new FileReader(INPUT));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
}
}
and the file /opt/java.policy like below
grant {
permission java.io.FilePermission "./out.txt", "write";
};
Then I run
java -Xss64m -Xms16m -Xmx512m -Djava.security.manager -Djava.security.policy=/opt/java.policy Main
But there are no errors, the output is what the in.txt is. I tried other file and got the same result. Why does this happen?
From the Javadoc:
Please note: Code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so.
Not that this is well-specified. Code isn't 'in' a directory: it is executed from a current working directory, and this appears to be what is meant.

Where does Java save files to?

I ran the below code and created a file. Where can I find it in my filesystem?
import java.io.*;
public class FileReaderDemo {
public static void main(String args[]) throws Exception {
File f = new File ("wayback.txt");
f.createNewFile();
System.out.println(f.exists());
}
}
Add the following to your program, run it and it'll show you the expected location:
System.out.println(f.getCanonicalFile());

Cannot open file in java

I am trying to open a text file in java. I am using ubuntu 12.04. Following is my code:
package nlp;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
public class sentence {
public static void main(String[] args) {
System.out.println("hello");
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
}
}
I am using Eclipse for development. It says "FileNotFound". I have put the text file in .class as well as .java folder. Where am I going wrong?
The default execution directory in Eclipse is the root of the project folder. Put the file there or prefix the path with correct underlying folder structure.
you need to put that in try-catch because it throws IOException which is checked Exception.Put the code in try-catch or handle the exception using "public static void main(String[] args) throws IOException"
The file should be in root of the project folder as given below. Your code is working fine.
As Arnaud mentioned try this to find where Java is expecting the file:
System.out.println(new File(".").getAbsolutePath());

regarding placing the txt file for java to read it right away

I want to read text and STORE it in a String variable ...
This code is working fine but i want to know where the txt file should be placed exactly for me to not specify the exact path. Since I'll be trying this code on various machines . so I hope you understood what I want.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Compress {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String text="";
try {
text = new Scanner( new File("C:\\Users\\sandhya\\workspace\\PrefixFreeCodeChecker\\src\\poem.txt"), "UTF-8" ).useDelimiter("\\A").next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(text+"");
}
}
Put your poem.txt file in your java project folder and change the path to this:
text = new Scanner( new File("poem.txt").....

Categories

Resources