I'm trying to take a word as input and check whether that word is present in a text file. But I ended up with this error.
import java.io.*;
public class SpellingChecker {
public static void test(String str) throws IOException{
FileReader fr = new FileReader("wordsEn.txt");
BufferedReader br = new BufferedReader(fr);
int i=0,j=0,n=str.length();
str+=' ';
String temp="",temp2="";
do{
for(i=j;str.charAt(i)!=' ';i++)
temp+=str.charAt(i);
System.out.println(temp);
while((temp2=br.readLine()) != null) {
if(temp==temp2)
System.out.print("\t\t\tOK");
else
System.out.print("\t\t\tWRONG");
}
temp="";
j=i+1;
}while(i<n);
fr.close();
}
public static void main(String[] args) throws IOException{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter string for which you want to check spelling : ");
String strng=input.nextLine();
test(strng);
}
}
Error is
Exception in thread "main" java.io.FileNotFoundException: wordsEn.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:131)
at java.io.FileInputStream.<init>(FileInputStream.java:87)
at java.io.FileReader.<init>(FileReader.java:58)
at SpellingChecker.test(SpellingChecker.java:5)
at SpellingChecker.main(SpellingChecker.java:29)
Only the name of the file will not do.You have to mention the path of the file while creating
the "FileReader" object.For example,if the path is "C:\wordsEn.txt",you should write:-
FileReader fr=new FileReader(new File("C://wordsEn.txt"));
Remember,if you use '\' in place of "//" "Illegal Escape Character" will be the error shown.
This should fix it.Give it a try...
You have to put your text file in the source directory.
Related
Trying to print the read() output of the same program on to the console, the characters are either missing or disarranged. Tried this for different files too, getting the same issue.
The byte Stream class and method,FileInputStream.read()for the same type of code, worked perfectly fine, but this character stream is resulting differently.
import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;
class CSRead1
{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(in);
out.print("Enter the filename\t>");
String file = input.next();
try(FileReader fr = new FileReader(file))
{ while(fr.read() != -1)
{out.print((char)fr.read());} } //***reading improperly
}
}
Got this upon execution:
D:\JavaEx\FILE-IO>java CSRead1
Enter the filename >CSRead1.java
ipr aaui.cne;
{asCRa1aaln.ytm*
pbi ttcvi anSrn[ rs hosIEcpin
{
cne nu e cne(n;
u.rn(Etrteflnm\>)
tyFlRae r=nwFlRae(ie)
hl(rra( =-)
{u.rn(ca)rra()}}/**edn mrpry
}
?
For a text file containing the only string "Hello"
D:\JavaEx\FILE-IO>java CSRead1
Enter the filename >sample
el?
You read two chars on every iteration: one in while condition and one in loop body. try to fix this issue and all your code will work fine.
I once had an issue with reading files with UTF-8 encoded characters in them.
The solution was:
String st;
File filedir = new File(filename);
BufferedReader in = new BufferedReader(new InputStreamReader(new
FileInputStream(filedir), "UTF8"));
while((st = in.readLine()) != null) {
System.out.println(st); //prints out properly on my side
}
within your code it would look something like this:
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(in);
out.print("Enter the filename\t>");
String file = input.next();
String st;
File filedir = new File(file );
BufferedReader in = new BufferedReader(new InputStreamReader(new
FileInputStream(filedir), "UTF8"));
while((st = in.readLine()) != null) {
System.out.println(st);
}
}
Given more than one files in a directory
I have to read only the text files from a directory and print all the information inside it.
My Implementation:
File filepath=new File("c:/test");
Pattern p=Pattern.compile("[a-zA-Z0-9_]+.txt");
String s1[]=filepath.list();
for (int i=0;i<s1.length;i++){
Matcher m=p.matcher(s1[i]);
if(m.find()&&m.equals(s1));
System.out.println(s1[i]);
File file1=new File(s1[i]);
readFromFile(file1);
}
static void readFromFile(File filename) throws IOException{
String line = null;
FileReader fileReader = new FileReader(filename); //1
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
fileReader.close();
}
While running the above program i am getting NullPointer at position 1 as indicated in the code.
Though I know the approaches using fileList method in file class I can read all the files in a directory and I also know that i can use endsWith method in String classto read only text file.
But I wanted to know how using above implementation I can read all the data inside the text files.
Can anyone guide me on this how to correctly handle the above approach.
You probably have a problem while reading the file.
To understand what problem exactly do you have - "file not found" or maybe "insufficient read permissions" - always catch and print the exception when opening files for reading or writing (and also for reading directories):
public static void main (String[] args) {
readFromFile(new File("nonexistant.txt"));
}
public static void readFromFile(File file) {
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
for (String line = bufferedReader.readLine();
line != null;
line = bufferedReader.readLine()) {
System.out.println(line);
}
} catch (Exception ex) {
System.err.print(ex);
}
}
Here it prints the reason:
java.io.FileNotFoundException: nonexistant.txt (No such file or directory)
Once you have fixed this issue, move to the file parsing.
Hi i am running java app from jar file. like following java -cp test.jar com.test.TestMain . in the java app i am reading csv file. which is throwing below exception.
java.io.FileNotFoundException: file:\C:\Users\harinath.BBI0\Desktop\test.jar!\us_postal_codes.csv (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at com.test.TestMain.run(TestMain.java:63)
at com.test.TestMain.main(TestMain.java:43)
*csv file is located in src/main/resources folder.
code causes to exception is
public static void main(String[] args) throws Exception {
TestMain trainerScraper = new TestMain();
trainerScraper.run();
}
private void run() throws JsonParseException, JsonMappingException, IOException{
String line = "";
String cvsSplitBy = ",";
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
System.out.println(csvFile);
URL url = classLoader.getResource("us_postal_codes.csv");
String fileName = url.getFile();
File file = new File(fileName);
try (Scanner scanner = new Scanner(file)) {
line = scanner.nextLine(); //header
while ((scanner.hasNextLine())) {
thanks.
test.jar!\us_postal_codes.csv (The filename, directory name, or volume
label syntax is incorrect)
Would suggest using
System.getProperty("user.dir") // to get the current directory, if the resource is in the project folder
and
getResourceAsStream("/us_postal_codes.csv") // if its inside a jar
Based on the stack trace below we can see that the Scanner cannot find the file:
at java.util.Scanner.<init>(Scanner.java:656)
at com.test.TestMain.run(TestMain.java:63)
By the way, where is the file? If it's in the jar, then you can use TestMain.class.getResourceAsStream() - Scanner has an InputStream constructor too:
InputStream iStream = TestMain.class.getResourceAsStream("/us_postal_codes.csv"); // this supposes the csv is in the root of the jar file
try (Scanner scanner = new Scanner(iStream)) {
//...
}
//...
You should use getResourceAsStream. This is example:
public void test3Columns() throws IOException
{
InputStream is = getClass().getResourceAsStream("3Columns.csv");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
CSVLineTokenizer tok = new CSVLineTokenizer(line);
assertEquals("Should be three columns in each row",3,tok.countTokens());
}
br.close();
isr.close();
is.close();
}
ClassLoader.getResource method is not used to search files in .jar archives.
In the below program, I have to first read a file and then write it. In the run configurations I provided the path of the file but when I run the program then it gives error: String index out of range: -1. ? Please help
public static void main(String[] args) throws IOException{
String fileName = args[0];
Scanner filescan;//to read the file
filescan=new Scanner(new File(fileName));//read the whole file
FileWriter fstream = new FileWriter(fileName.subSequence(0,fileName.indexOf(".uniqe.ICext"))+".uniqe.Mpwm");
BufferedWriter mpwm = new BufferedWriter(fstream);
you should add validations before use substring. otherwise it will eventually throw an Exception
int i= fileName.indexOf(".uniqe.ICext");
if(i<0)
//file name can't substring or handle exception
else
FileWriter fstream = new FileWriter(fileName.subSequence(0,i)+".uniqe.Mpwm");
For the purpose of this class task, we have been asked to make a program that uses the File Class(I know input stream is much better) but yeah, we have to ask the user to input the name of the .txt file.
public class input {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
String name;
int lineCount = 0;
int wordCount = 0;
System.out.println("Please type the file you want to read in: ");
name = s.next();
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
How would I get
File input = new File(...);
to search for the file as just typing 'lab1task3' doesn't work.
edit: error -
Exception in thread "main" java.io.FileNotFoundException: \lab1task3.txt (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 inputoutput.input.main(input.java:19)
Scanner can't read in files that way, you need to store it as a file first!
If you put this inside of a try-catch block, you can ensure that the program won't break if a file isn't found. I would suggest wrapping it in a do-while/while loop (depending on structure), with the end condition being that the file is found.
I changed your main method to this and it compiles correctly:
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner (System.in);
System.out.println("Please type the file you want to read in: ");
String fname = sc.nextLine();
File file = new File (fname);
sc.close();
}
To search for a file inside a specific folder, you could just iterate over the files inside the given folder via:
File givenFolder = new File(...);
String fileName = (...);
File toSearch = findFile(givenFolder, fileName);
Where the function findFile(File folder, String fileName) would iterate over the files in the givenFolder and try to find the file. It could look like this:
public File findFile(File givenFolder, String fileName)
{
List<File> files = getFiles();
for(File f : files)
{
if(f.getName().equals(fileName))
{
return f;
}
}
return null;
}
The function getFiles is just iterating over all files in the given folder and calls it self when finding a folder:
public List<File> getFiles(File givenFolder)
{
List<File> files = new ArrayList<File>();
for(File f : givenFolder.listFiles())
{
if(f.isDirectory())
{
files.addAll(getFiles(f));
}
else
{
files.add(f);
}
}
}
I hope this helps you :) If you want to know more about what happens here exactly feel free to ask :)