So I need help fixing this code, or more so understanding its faults. The code itself is supposed to read a file and print out the of occurrence of a string of words. However, it seems that it always prints out "Can't find file" even when the .txt file is on my desktop.
import java.util.*;
import java.io.*;
/**
* Searcher
*/
public class Searcher extends File {
Scanner scn;
public Searcher(String filename) {
super(filename);
}
public void search(String input) {
try {
scn = new Scanner(this);
String data = "";
while (scn.hasNext()) {
data = scn.nextLine();
}
int count = 0, fromIndex = 0;
while ((fromIndex = data.indexOf(input, fromIndex)) != -1) {
count++;
fromIndex++;
}
System.out.println("Total occurrences: " + count);
scn.close();
} catch (Exception e) {
System.out.println("Cant find file ");
}
}
public static void main(String[] args) {
Searcher search = new Searcher("ihaveadream.txt");
search.search("slavery");
}
}
Use the full path for the .txt file or move it into the same folder as the rest of your project. The program won't check the desktop (even if the folder is in the desktop).
You can use a more elegant way to read the file using the Stream API:
Files.lines(Paths.get("/home/userName/Desktop/text.txt"))
.forEach(System.out::println);
Depending on the operating system, there will be different paths, but there must be an absolute path to the file.
If you do not want to create a file on your OS desktop, you can just create a file on IDE on a package in which the current class is, then indicate the file directory on main method: in my case : src/practice/ihaveadream.txt
public static void main(String[] args) {
Searcher search = new Searcher("src/practice/ihaveadream.txt");
search.search("slavery");
}
I use IntelliJ Idea Community, so you can see how to create a file on Idea:
use this code
File file = new File("C:\\Users\\abc\\Desktop\\test.txt");// this is a path of your file
BufferedReader br = new BufferedReader(new FileReader(file));
String str;
while ((str = br.readLine()) != null)
System.out.println(str);
Related
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file.
Please log the file.getAbsolutePath() to verify that file is correct.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.
Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.
Im trying to read a simple text file with contents
input.txt
Line 1
Line 2
Line 3
But it always goes to the exception and prints Error.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR");
}
}
}
Im using Eclipse as my IDE if that makes a difference. I've tried this code on http://www.compileonline.com/compile_java_online.php
and it runs fine, why wont it run in Eclipse?
give complete file path like "C:\\folder_name\\input.txt" or place input.txt inside src directory of eclipse project.
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(
new FileReader("input.txt")); //<< your problem is probably here,
//More than likely you have to supply a path the input file.
//Something like "C:\\mydir\\input.txt"
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR"); //This tells you nothing.
System.out.println(e.getMessage()); //Do this
//or
e.printStackTrace(); //this or both
}
}
}
You most likely have a bad path. Consider this main instead:
public class Main {
public static void main(String args[]) throws Exception {
List<String> text = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}
}
The "throws Exception" addition allows you to focus on the code, and consider better error handling later. Also consider using File f = new File("input.txt") and use that, because it allows you to print out f.getAbsolutePath() which tells you the filename it was actually looking for.
Changing input.txt to src\\input.txt solved the problem!
I guess it was because the current directory isnt actually the src folder its the parent,
Thanks for the help!
I have a text file in my desktop named "MyText.txt" and it have some contents in it.
Since i am learning JAVA i thought of simply creating an console application which will read the contents from the txt file and then show it in console.
But since i am new to this ,so i am unable to figure out the way it works.
Can anyone get me into a right direction.
All help will be appreciated.
There are many alternatives for doing this. A higher level thing could be using a Scanner class. I assume, since you are learning java, you might have come across Scanner class for reading the input from console. You can use the Scanner same way to read the file also.
You can use Scanner#nextInt(), Scanner#next(), etc... methods for reading the input. You can use args[] array for taking the command line arguments.
Since, you haven't mention exactly what kind of way your data is stored in file, it's hard to give a working example.
import java.util.Scanner;
public class Tester {
public static void main(String args[]) {
if (args.length > 0) {
Scanner sc = new Scanner(new File(args[0]));
//use here the functions such as sc.nextInt() and so on
}
}
}
Link to the docs: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
If you are reading big file in java (see my answer to other question): file size too big for java:
Working Example:
This program prints the file contents to console.
Execute this program using java Tester yourFileName after compilation.
import java.util.*;
import java.io.*;
public class Tester {
public static void main(String args[]) {
try {
if (args.length > 0) {
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNext()) {
System.out.println(sc.next());
}
} else {
System.out.println("No file name given");
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}
You can try the following example to read file character basis.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package io;
import java.io.*;
/**
*
* #author Nandeshwar
*/
public class FileExample {
public static void main(String[] args) {
File inFile = new File("c:/users/toshiba/desktop/MyText.txt");
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.println((char) ch);
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
ins.close();
} catch (Exception e) {
}
}
}
}
This should help. Create a BufferedReader object like this:
new BufferedReader(new FileReader("Location of the file"));
Read this doc, for reference: http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file.
Please log the file.getAbsolutePath() to verify that file is correct.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.