I have coded the following for reading a txt in Java:
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String name;
String line;
System.out.println("Input file name");
Scanner inp=new Scanner(System.in);
name=inp.nextLine();
FileReader file=new FileReader(name);
BufferedReader br=new BufferedReader(new FileReader(name));
while((line=br.readLine())!=null){
System.out.println(br.readLine());
}
br.close();
}
I have a txt file that is under the same folder of my java code, its name is data.txt (which contains a list of numbers line by line), the problem that I got is that when I run this I got the following message:
Exception in thread "main" java.io.FileNotFoundException: data.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
where is the mistake? also how I can surround it with a try catch block in case the file does not exist?
I have put the System.out.println(new File(name).getAbsoluteFile); and it appears all the path thru data.txt, but I want to point by default to my current folder; should I use Scanner?
If you want to use the relative file name and you're running from an IDE like netbeans or eclipse, you file structure should look something like this
ProjectRoot
file.txt
src
build
file.txt being the relative path you're using. The IDE will first search the Project root for the file if no other directories are specified in the file path.
If youre using a scanner, you need to use the File
Scanner inp=new Scanner(System.in);
name=inp.nextLine();
File file = new File(name);
if(file.exists()) {
try {
FileReader file=new FileReader(name);
BufferedReader br=new BufferedReader(new FileReader(name));
while((line=br.readLine())!=null){
System.out.println(br.readLine());
}
br.close();
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
that should help, hope it does :)
Related
I've been trying to read the text file in my java projects, I've been looking for the solution for the whole day, I've tried loads of methods but none of them have worked. Some of them:
(Also, I have to use File and Scanner class)
String file = "fileTest.txt";
var path = Paths.get("test", file);
System.out.println(path);
System.out.println(Files.readString(path));
Exception in thread "main" java.nio.file.NoSuchFileException:
test\fileTest.txt
URL url = ClassLoader.class.getResource("fileTest.txt");
File file = null;
file = new File(url.toURI());
Scanner scanner = new Scanner(file);
scanner.useDelimiter(" ");
while(scanner.hasNext()) {
System.out.println(scanner.toString());
}
Exception in thread "main" java.lang.NullPointerException
File file = new File("../test/fileTest.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter(" ");
while(scanner.hasNext()) {
System.out.println(scanner.toString());
}
scanner.close();
Exception in thread "main" java.io.FileNotFoundException: ..\test\fileTest.txt (The system cannot find the path specified)
The problems here are project structure and how you're trying to locate that file. Conventionally, your java class files should exist within the directory src/main/java and your resource files should exist within src/main/resources. If you follow this convention, you can obtain the resource with a ClassLoader.
try (InputStream input = getClass().getClassLoader().getResourceAsStream("test.txt");
Scanner scanner = new Scanner(Objects.requireNonNull(input)).useDelimiter(" ")) {
while(scanner.hasNext()) {
System.out.println(scanner.toString());
}
} catch (IOException ioe) {
throw new RuntimeException("Something went wrong scanning file!", ioe);
}
All of the answers talking about relative paths are going to work or not work depending on what your working directory is when you are running your program. If you truly want your file to live inside the classpath, what you want to do is use it as a resource and look on how to load resources at runtime. If, on the other hand, you want to treat it just like any other file, you will need to know what the working directory is at runtime if you expect any relative pathing to work, or have the absolute path specified at some known place, like a configuration file.
Reading a file with BufferReader, using try-with-resource which automatically closes the resources when processing has terminated.
See info on Java try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Edit: Ensure you have included the folder as a resource in your build path. How do I add a resources folder to my Java project in Eclipse
String inputFile = "test/fileTest.txt";
List<String> lines = new ArrayList<>();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Replace
File file = new File("../test/fileTest.txt");
Scanner scanner = new Scanner(file);
with
File file = new File("test/fileTest.txt");
Scanner scanner = new Scanner(file);
Then, if you want to confirm it, just do the following:
System.out.println(file.exists());
Also, replace
while(scanner.hasNext()) {
System.out.println(scanner.toString());
}
with
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
because scanner.toString() can not be used to get an input; it should be scanner.next().
What I am trying to do here is read a text file from my system and print it's contents in java
I have also tried giving permissions to folder in which it is present please have a look at my code:
public class Rtree {
public static void main(String... args)
{
// ArrayList<String> st=new ArrayList<String>();
try{
FileReader file=new FileReader("D://Qos Logs");
//DataInputStream In=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(file);
String s;
while((s =br.readLine()) !=null){
// text=
System.out.println(s);
}
br.close();
// In.close();
} catch(Exception e){
System.err.println("Error:"+e.getMessage());
}
}
}
There are many ways of reading the file, but I'll show the simplest one. Use \\ slash when you give the full path of your file. Separating the folders and your file name by \\.
Try doing this in your code :
FileReader file=new FileReader("D:\\path of your file\\ 20111123.txt");
You can read data using File and Scanner class simply pass the address of the file in File class Constructor and used the object of a class in your Scanner constructor next code in front of you.
try {
File file = new File("Path of your file include file name with extension like C:\\Users\\kashi\\Desktop\\DNA.txt");
if(file.exists()){
System.out.println("yes");
Scanner readFile = new Scanner(file);
if(file.canRead()){
System.out.println("yes you can read it");
if(readFile.hasNext()){
System.out.println(readFile.nextLine());
}
}
}else {
System.out.println("No");
}
}catch (Exception e){
System.out.println(e.getMessage());
}
I am trying to read from a text file using BufferedReader and FileReader and I am constantly running into this problem:
java.io.FileNotFoundException: dicomTagList.txt (The system cannot find the file specified)C:\temp\workspace\DICOMVALIDATE\dicomTagList.txt
I can't seem to find out why this is occurring when I have that file in the correct directory and was able to even verify it with getAbsolutePath() Method in FileReader.
Can anyone advise why this may be?
Here is my code snippet:
public void readFromTextFile(File path) throws IOException
{
try
{
System.out.println(dicomList.getAbsolutePath());
String line;
BufferedReader bReader = new BufferedReader(new FileReader(dicomList));
while( (line = bReader.readLine()) != null)
{
System.out.println(line);
}
bReader.close();
}
catch(FileNotFoundException e)
{
System.err.print(e);
}
catch(IOException i)
{
System.err.print(i);
}
}
Are you sure that the file really exists? What will the following expression print:
dicomList.exists();
In Java java.io.File is representing just a path to a file, not necessarily a real file. This means you can create File object even if the underlying path does not exist.
Hi I am trying to set up a scanner to print out contents of a text file. Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile {
public static void main(String[] args) {
// Location of file to read
File file = new File("CardNative.java.txt");
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
I have created a source folder in the project and put the text file in there. However I keep getting this error:
java.io.FileNotFoundException: CardNative.java.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at ScannerReadFile.main(ScannerReadFile.java:14)
You can use use System.out.println(System.getProperty("user.dir")); to see on what folder Java is looking by default for the file. If the file doesn't exist there you have to specify the entire path to the file.
This should work.
public static void main(String[] args) {
Scanner scanner = new Scanner(ScannerReadFile.class.getResourceAsStream("CardNative.java.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}
You need to make sure that your file is placed in the same directory from where you're running your program. Try adding this at the top of your main function, to see what's the current directory, and if your file is actually in that directory:
System.out.println(System.getProperty("user.dir"));
new File(String pathname);
The coinstructor you are using takes filepath as an argument, absolute or relative. If it is relative, it will be the execute path/your_string.
So you should put the file to the same folder as the compiled .jar file.
File file1 = new File("text.txt");
File file2 = new File("D:/documents/test.txt");
If the programm is executing from C:/programms/myprj.jar, so
file1 will open "C:/programms/test.txt" and file2 will open "D:/documents/test.txt" independently of the executing path.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html#File(java.lang.String)
I was posting my answer in comment but I am not allowed to comment because I have no enough reputations. As in your comment, you are using back slashes in the file path. Instead use double back slashes \ OR one forward /. eg C:/java/file.txt
You should provide it the right and actual path of the file OR make sure that the file is lying there where your source is.
public class ScannerReadFile {
public static void main(String[] args) {
// Location of file to read
File file = new File("C:/Users/EastCorporation/Desktop/CardNative.java.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
i put this code,which i got from the internet, in my java program but when i try to delete, the original file cannot be deleted and the temporary file cannot be renamed to the original file.The two files remains in the folder with its contents unchanged.
...
public class FilingDatabase {
public static void main(String[]args)throws IOException{
(new FilingDatabase()).run();
FilingDatabase fd=new FilingDatabase();
String word = null;
fd.delete("person.txt",word);
}
.
public void run() throws IOException{
File file=new File("person.txt");
BufferedReader br=new BufferedReader(new FileReader(file));
while((str=br.readLine())!=null)
i++;
System.out.print("\t\t\t\t\t\t***************WELCOME*****************");
System.out.println();
System.out.println("1. Add \n2. Edit \n3. Delete \n4. Exit");
System.out.print("\nEnter option number: ");
option=in.next();
while(true){
...
else if(option.charAt(0)=='3'){
// FilingDatabase fd= new FilingDatabase();
System.out.print("Enter word: ");
word=in.next();
//delete("person.txt",word);
}
...
}
}//end of fxn run()
....
public void delete(String file, String lineToRemove) throws IOException{
try {
File inFile = new File(file);
if (!inFile.isFile()){
System.out.println("File does not exist");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
//Scanner br=new Scanner(file);
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I'm not sure where you're trying to delete, but on the last line of your main:
fd.delete("person.txt",word);
will not delete anything because Object.equals(null) should always return false. (word is null.)
If you're trying to delete inside your loop:
// FilingDatabase fd= new FilingDatabase();
System.out.print("Enter word: ");
word=in.next();
//delete("person.txt",word);
It won't delete anything because the delete line is commented out.
I'm not sure what to tell you about deleting and renaming the files, because that works for me.
I'm not going to try to get my head around your code ... and what it is trying to do. (Have you heard of comments? Javadocs? Have you considered using them?)
However, I'd like to point out that both delete and rename can fail under a number of circumstances. In the delete case, these include the following:
the target file does not exist
the target file does exist but the application doesn't have permission to access the parent directory and/or delete the file
the target object is a directory not a file
(on some platforms) the target file is locked because this application or another one currently has it open.
In the case of rename, you have to consider the existence, permissions, etc of the file being renamed (and its parent directory) and the directory you are trying to move. And there's also the issue that rename doesn't work between different file systems.
It is unfortunate that these methods (on the File class) don't say why the delete or rename failed. (The methods on the new Java 7 Files class do ...) Even if they were able to do this, the diagnostics would be limited by what the OS syscalls report. In the case of Unix / Linux, this is pretty limited.