Read an existing text file in Java - java

I'm a Java Beginner and I'm trying to make a program of reading from an existing text file. I've tried my best, but it keep on saying "File Not Found!". I've copied my "Test.txt" to both the folders - src and bin of my package.
Kindly help me into this. I'll be very thankful. Here's the code -
package readingandwritingfiles;
import java.io.*;
public class ShowFile {
public static void main(String[] args) throws Exception{
int i;
FileInputStream file_IN;
try {
file_IN = new FileInputStream(args[0]);
}
catch(FileNotFoundException e) {
System.out.println("File Not Found!");
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i = file_IN.read();
if(i != -1)
System.out.print((char)i);
} while(i != -1);
file_IN.close();
System.exit(0);
}
}

If you are just putting Test.txt then the program is looking in the root folder of the project. Example:
Project
-src
--package
---class
-bin
-Test.txt
Test.txt needs to be in the same directory as src and bin, not inside of them

If your folder structure is like this (The Text.txt file inside src folder)
+src
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("Text.txt").getFile());
file_IN = new FileInputStream(file);
Or If your folder structure is like this
+src
+somepackage
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("/somepackage/Text.txt").getFile());
file_IN = new FileInputStream(file);

Pass a String (or File) with the relative path to your project folder (if you have your file inside src folder, this should be "src/Test.txt", not "Test.txt").
For read a text file you should use FileReader and BufferedReader, BufferedReader have methods for read completed lines, you can read until you found null.
An example:
String path = "src/Test.txt";
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
}

Tons of ways to accomplish this! I noticed that you specify args[0], why?
// Java Program to illustrate reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file =
new File("C:\\Users\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}

Related

FileNotFoundException but File present at right path

I'm new to programming, every time I try to read a file. I get FileNOtFoundException.
Where could I be going wrong?
import java.io.*;
import java.util.Scanner;
public class ReadFile
{
public ReadFile()
{
readFile();
}
public void readFile()
{
String filename = "trees.txt";
System.out.println(new File(".").getAbsolutePath()); //file is at this path.
String name = "";
try
{
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
while (parser.hasNextLine())
{
name = parser.nextLine();
System.out.println(name);
}
inputFile.close();
}
catch (FileNotFoundException exception)
{
System.out.println(filename + " not found");
}
}
}
Is there any other way I could read the file?
this code
FileReader inputFile = new FileReader(filename);
You must define full path to file with name filename if not it will open file not at current working directory
you should try
FileReader inputFile = new FileReader(new File(new File("."), filename));
// defind new File(".") it mean you will you open file in current working directory
you can read more at: Java, reading a file from current directory?
Try printing the path of the file you are actually trying to open so you can be sure that the file exists in the right location
String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());
Also, you are closing the FileReader inside the try, and not closing the Scanner, if some error ever occurs those resources will never be closed, you need to put those close statements in a finally block, or better use try with resources

FileReader won't read second file in a list

I put two files in a directory and tested to see if my code can search through the files and find a match, but the FileReader won't read the second file. Here is my code and my console entry. I have narrowed the error down to the FileReader, but I don't know how to fix that.
public class Main
{
public static void searchEngine(String dir, String Search)
{
File folder = new File(dir);
String[] files = folder.list();
Integer f1 = 0;
FileReader fileReader;
ArrayList linematches;
BufferedReader bufferedReader;
Integer q;
String line;
Integer linenum;
System.out.println("Found Files:");
for (String file : files) {
System.out.println(file);
}
try {
for (String file : files) {
linematches = new ArrayList();
fileReader = new FileReader(files[f1]);
bufferedReader = new BufferedReader(fileReader);
linenum = 0;
while ((line = bufferedReader.readLine()) != null) {
linenum += 1;
if (line.contains(Search)) {
linematches.add(linenum);
}
}
q = 0;
for (int i = 0; i < linematches.size(); i++) {
System.out.println("File: " + file + " Line: " + linematches.get(i));
}
linematches.removeAll(linematches);
// Always close files.
bufferedReader.close();
f1++;
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + dir + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + dir + "'");
}
}
public static void main(String[] args)
{
while (true) {
System.out.println("Enter the search term: ");
Scanner scanner = new Scanner(System.in);
String searchterm = scanner.nextLine();
System.out.println("Enter each file location: ");
String f1 = scanner.nextLine();
searchEngine(f1, searchterm);
}
}
}
Here is the output of my console:
Enter the search term:
bla
Enter each file location:
test dir
Found Files:
testfile.txt
testfile2.txt
Unable to open file 'test dir'
The entire stack trace of the error is:
Unable to open file 'testfile2.txt' java.io.FileNotFoundException:
testfile2.txt (No such file or directory) Enter the search term: at
java.io.FileInputStream.open0(Native Method) at
java.io.FileInputStream.open(FileInputStream.java:195) at
java.io.FileInputStream.(FileInputStream.java:138) at
java.io.FileInputStream.(FileInputStream.java:93) at
java.io.FileReader.(FileReader.java:58) at
com.mangodev.Main.searchEngine(Main.java:32) at
com.mangodev.Main.main(Main.java:70)
Please help. Thank you.
It looks to me as if you have the following folder structure:
Main.class
Main.java
test dir
|-- testfile.txt
|-- testfile2.txt
You run the code from the directory containing Main.class, Main.java and test dir. Your code then lists files in the directory test dir, finding the two text files it contains, but then attempts to open them from the current directory. This is the parent directory, and of course, this isn't where those files are. They are in the sub-directory test dir. A FileNotFoundException is therefore to be expected: you're attempting to open a file in the wrong directory.
If the FileReader happens to fail on the second of the two files, does there happen to be a file testfile.txt in the parent directory as well? Your code may well have been opening this file first time through the loop instead of the one in test dir that you thought it was.
To open files within the test dir subdirectory, replace the line
fileReader = new FileReader(files[f1]);
with
fileReader = new FileReader(new File(dir, files[f1]));
In your first line in the searchEngine method you create a variable folder that contains the files in the directory. I suggest using this variable directly in your for loop instead of string filenames.
for (File file : folder.listFiles()) {
linematches = new ArrayList();
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
//rest of code...
}

Reading a file from my desktop and printing each line from it

dear all here i have this code:
File file = new File("flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
String line = in.nextLine();
System.out.println(line);
I want to read from a file and print each line, but this code doesn't work because of some exceptions (throw exception??), how can i put it in a way that it would read from the flowers.txt file, which is on my desktop and will print each line from this file in the console?
Recheck your code
File file = new File("flowers_petal.txt"); // This is not your desktop location.. You are probably getting FileNotFoundException. Put Absolute path of the file here..
while(in.hasNext()){ // checking if a "space" delimited String exists in the file
String line = in.nextLine(); // reading an entire line (of space delimited Strings)
System.out.println(line);
SideNote : use FileReader + BufferedReader for "reading" a file. Use Scanner for parsing a file..
Here you go.. Full code sample. Assuming you put you file in C:\some_folder
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String args[]) {
File file = new File("C:\\some_folder\\flowers_petal.txt");
Scanner in;
try {
in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are checking for the wrong condition, you need to check for hasNextline() instead of hasNext(). So the loop will be
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
Consider these 2 points :
the current location you are giving in your file is not valid (if
your .java (source) file is not on Desktop), so give the full path
for your file.
the new Scanner(File file) throws FileNotFoundException, so you have to put the code in try-catch block or just use throws.
Your code may look like this :
try {
File file = new File("path_to_Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e){
e.printStackTrace();
}
try this
public static void main(String[] args) throws FileNotFoundException {
//If your java file is in the same directory as the text file
//then no need to specify the full path ,You can just write
//File file = new File("flowers_petal.txt");
File file = new File("/home/ashok/Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
System.out.println(in.nextLine());
}
in.close();
}
NOTE :I am using linux ,If you are using windows your desktop path would be different
Try this................
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
give your exact path in the FileReader("exact path must be here...")
source: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

Cannot find file on netbeans

I'm trying to access a data file to get questions and answers for my "Quiz" application.
If I access the file from the one on my desktop, it works fine. If I drag and drop the file into my netbeans, I cannot seem to access it.
The file is in the package "quiz" along with my other classes.
Here's the code that works but I want to use the netbeans file.
String fileName = "C:/Users/Michael/Desktop/QUIZ.DAT";
try {
//Make fileReader object to read the file
FileReader file = new FileReader(new File(fileName));
BufferedReader fileStream = new BufferedReader(file);
} catch (Exception e) {
System.out.println("File not found");
}
To try and access the file on netbeans I use this but it cannot find it.
String fileName = "quiz/Quiz.DAT";
Try this, where MyClass is the class name. I have assumed the quiz.dat file is in the same package of the class.
InputStream f = MyClass.class.getResourceAsStream("QUIZ.DAT");
BufferedReader bReader = new BufferedReader(new InputStreamReader(f));
StringBuffer sbfFileContents = new StringBuffer();
String line = null;
while ((line = bReader.readLine()) != null) {
sbfFileContents.append(line);
}
System.out.println(sbfFileContents.toString());
JJPA provided proper code. But let me enhance it better.
Project
com.io
test.txt
com.root
AccessFile.java
This is my program structure. I want to access file from package io So here is the code.
package com.root;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class AccessFile {
public static void main(String args[]){
try{
InputStream f = AccessFile.class.getResourceAsStream("../io/test.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(f));
StringBuffer sbfFileContents = new StringBuffer();
String line = null;
while ((line = bReader.readLine()) != null) {
sbfFileContents.append(line);
}
bReader.close();
f.close();
System.out.println(sbfFileContents.toString());
}catch(Exception e){
e.printStackTrace();
}
}
}
If you are trying to read a file in your JAVA project and netbeans is not able to find it, put the file in the root directory of your project and it should be able to find it.

My method can't find files in directory

public class Cww {
static List<String> readFile(String filename) {
List<String> records = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while((line = reader.readLine()) != null)
{
records.add(line);
}
reader.close();
return records;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
and my main:
readFile("DirList.java");
File file = new File("DirList.java");
System.out.println(file.getCanonicalPath());
// CLASSPATH: .;..;J:\Programowanie\eclipse workspace\tij;C:\Program Files\Java\jre7\lib\ext\QTJava.zip
output: java.io.FileNotFoundException: DirList.java (Nie można odnaleźć określonego pliku)
J:\Programowanie\eclipse workspace\Rozdzial 18 cwiczenia\DirList.java
file.getCanonicalPath() shows that jvm search for my file where it really is, but my fileRead method is still giving me error,
Do I need to include every project folder in my classpath to read files from them ?
Thanks in advance
The File constructor argument is an absolute or relative filename. It will not use the classpath, the filename is - if not absolute - always relative to the current working directory.
FileReader(filename) will open a "DirList.java" in the directory from where your java code was executed (relative path). It is not related to the CLASSPATH in any way.

Categories

Resources