reading txt file and writing a dictionary - java

My objective is to eventually make a spell checker but I need a dictionary of words to do that.
Here I'm trying to allow the user to input any number of text files as long as there's a space in between the file names ("novel1.txt novel2.txt novel3.txt").
I will use every word from these novels to write to a .dat file of individual words on individual lines(i.e. a dictionary of words). However I'm getting a file not found error at Scanner read = new Scanner(new File(filenames[i])); even though I know that I have the file.
I have even tried putting it in the source package to make sure it could be found.
At the very bottom of my code is a small test I ran (commenting out the other code first) and it does indeed print "war.txt isn't a file," even though I can clearly see that I have the txt file and have typed it correctly.
Can somebody tell me why java isn't seeing my txt file or maybe doesn't think it is a normal file?
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the file names exactly.");
String userInput = in.nextLine();
String[] filenames = userInput.split(" "); // turning user input string into a string array so I can look at each string individually
// takes each individual string from filenames and turns each one into the file
// that the string should represent then adds the file's contents to my dictionary
for(int i = 0; i < filenames.length; i++){
Scanner read = new Scanner(new File(filenames[i]));
String word = null;
while(read.hasNext()){
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
}
}
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
}

I believe you do something in a wrong way. Try following example and compare it with your actual file locations.
Demo.java
import java.io.*;
class Demo {
public static void main(String[] args) throws IOException {
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
} else {
System.out.println(war + " is a file.");
}
}
}
compile and run it
javac Demo.java
java Demo
output
war.txt isn't a file.
now create in the same directory the war.txt
echo "foobar" > war.txt
run the code again
java Demo
output
war.txt is a file.

For the FileNotFoundException make sure that files are in your classpath if you insert only the filenames (for example if you use eclipse put the files on the root folder of the project).
For the war.txt issue you should do this:
File war = new File("war.txt");
if (!war.exists()) {
war.createNewFile();
}
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
This because when you do File war = new File("war.txt"); you are not creating the file, you have to explicitily create it with war.createNewFile();.
Finally, pay attention here:
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
You do two times read.next() without check read.hasNext() the second time. You should write something like that:
while(read.hasNext()){
String next = read.next();
if(next.length() >= 2){
word = next;
// write word into myDict.dat
}
System.out.println(word);
}

Related

How to access directory with full file path?

So, I'm writing a program that needs to iterate through all files in a directory and here is what I currently have.
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws Exception {
VotingData v = new VotingData();
Scanner in = new Scanner(System.in);
System.out.print("Please input a directory.");
String input = in.next();
File dir = new File(input);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
v.merge(RecordReader.readRecord(child.toString()));
}
}
else {
// do nothing right now.
}
String[] sub1 = {"Montgomery","Miami"};
TextualRepresentation.toString(v.getAllResults());
TextualRepresentation.toString(v.getCountyResults("Montgomery"));
TextualRepresentation.toString(v.getCountyResults("Miami"));
TextualRepresentation.toString(v.getCountyResults("Butler"));
TextualRepresentation.toString(v.getSubsetResults(sub1));
}
}
The filepath of the project is C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff.
The input I'm trying is "C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles" , but it doesn't seem to work. However, when input is just "TestFiles" it does. I want to be able to access directories in different folders, but for some reason the long method isn't working.
Edit: I don't know what the error is. All I know is when I put "TestFiles" into the Scanner it works fine and when I try the full file path it doesn't crash, but it doesn't yield the results I want.
Scanner#next() reads white-space delimited (by default) string tokens.
Your input:
C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles
Contains spaces, so next() just reads "C:\Users\Jarrett".
You can use Scanner#nextLine() instead.
In the future, to debug on your own, either step through in a debugger to see what values variables have, or add print-outs to verify, e.g. this would have led you to a solution quickly:
System.out.println("input was " + input);

Why am I getting an error when it tries to read from the file?

I am writing a program that can encode and decode messages using classical encryption methods. The message is to be read in from a file and written to an output file. The following program is written in java and compiles with no errors. When I run the program to test if it works so far after I give it the names of the input and output file it runs into some kind of exception throwing error. I assume the issue lies in the for loop that follows in the code. It is a loop to store all of the message into an array of characters. Any suggestions to fix it or another data structure that would work better (like a stack or queue)?
import java.io.*;
import java.util.*;
class CryptoProject1
{
static char eord;
static Scanner cin=new Scanner(System.in);
static char [] message=new char[10000];
public static void main (String [] args)
throws IOException
{
//getting the input txt file name from user
String infilename;
System.out.println("Please give the name of the input file.");
infilename=cin.nextLine();
Scanner fileread=new Scanner (new FileReader(infilename));
//getting the output txt file name from user
String outfilename;
System.out.println("Please give the name of the output file.");
outfilename=cin.nextLine();
PrintWriter filewrite=new PrintWriter(new FileWriter(outfilename));
//saving the message into an array
//construct/make it into a usable function??
for(int i=0; i<message.length; i++)
{
message[i]=fileread.next().charAt(0);
}
//trial to make sure it reads and writes correctly
//printing the message onto the output file
for(int i=0; i<message.length; i++)
{
filewrite.print(message[i]);
}
}
for(int i=0; i<message.length; i++)
{
message[i]=fileread.next().charAt(0);
}
Here, you cannot know if file length is same or higher than message, file may as well have 10 characters. You need to do that:
for(int i=0; i<message.length; i++)
{
if(!fileread.hasNext())
break;
message[i]=fileread.next().charAt(0);
}
Just a simple check if there is still something to be read from file, if not then stop reading.
Also it is customary to use the Java object File to represent files rather than using string to hold the file path. Example:
private File output;
public void create file(String path)
{
output = new File(path);
}
private BufferedWriter out = new BufferedWriter(new FileWriter(output));
Also, whenever you write to a file, make sure you close it by calling the close() method or its contents wouldn't be saved
//I ran this code without an error
//getting the input txt file name from user
String infilename;
System.out.println("Please give the name of the input file.");
infilename=cin.nextLine();
Scanner fileread=new Scanner (new FileReader(infilename));
//getting the output txt file name from user
String outfilename;
System.out.println("Please give the name of the output file.");
outfilename=cin.nextLine();
PrintWriter filewrite=new PrintWriter(new FileWriter(outfilename));
//saving the message into an array
//construct/make it into a usable function??
for(int i=0; i<message.length; i++)
{
if(fileread.hasNext())
message[i]=fileread.next().charAt(0);
}
fileread.close();
//trial to make sure it reads and writes correctly
//printing the message onto the output file
for(int i=0; i<message.length; i++)
{
filewrite.print(message[i]);
}
filewrite.close();
}

the system cannot find the file specified even though input is in same directory as java code

I am trying to run this code and I get error as the system cannot find the file specified. My file is in the same directory as the code. I am specifying the full path name also. So what is the problem?
public class StopWordsSol
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
// ask for the stop words file name and read in stop words
System.out.print("Please type the stop words file name: ");
String[] stopWords = readStopWords(keyboard.next());
// ask for the text file and remove stop words
System.out.print("Please type the text file name: ");
removeStopWords(keyboard.next(), stopWords);
}
// read stop words from the file and return an array of stop words
public static String[] readStopWords(String stopWordsFilename)
{
String[] stopWords = null;
try
{
Scanner stopWordsFile = new Scanner(new File(stopWordsFilename));
int numStopWords = stopWordsFile.nextInt();
stopWords = new String[numStopWords];
for (int i = 0; i < numStopWords; i++)
stopWords[i] = stopWordsFile.next();
stopWordsFile.close();
}
catch (FileNotFoundException e)
{
System.err.println(e.getMessage());
System.exit(-1);
}
return stopWords;
}
}
This is a quite common problem: the base-directory of the program is usually not the same as the directory the source-code is stored in. Try the following lines:
Path cd = Paths.get("");
System.out.println("cd= " + cd.toAbsolutePath());
Which will print the working-directory of your program.

Finding and replacing words in a text file with Scanner and Printwriter classes

I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.

Comparing user input string to string read from text file

I'm currently writing this program that I require to read info from a text file and to then compare the info read to a user input and output a message saying if it was a match or not.
Currently have this. The program is sucessfully reading the data specified but I can't seem to compare the strings correctly at the end and print a result.
Code is below any help would be greatly appreciated.
import java.util.Scanner; // Required for the scanner
import java.io.File; // Needed for File and IOException
import java.io.FileNotFoundException; //Required for exception throw
// add more imports as needed
/**
* A starter to the country data problem.
*
* #author phi
* #version starter
*/
public class Capitals
{
public static void main(String[] args) throws FileNotFoundException // Throws Clause Added
{
// ask the user for the search string
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter part of the country name: ");
String searchString = keyboard.next().toLowerCase();
// open the data file
File file = new File("CountryData.csv");
// create a scanner from the file
Scanner inputFile = new Scanner (file);
// set up the scanner to use "," as the delimiter
inputFile.useDelimiter("[\\r,]");
// While there is another line to read.
while(inputFile.hasNext())
{
// read the 3 parts of the line
String country = inputFile.next(); //Read country
String capital = inputFile.next(); //Read capital
String population = inputFile.next(); //Read Population
//Check if user input is a match and if true print out info.
if(searchString.equals(country))
{
System.out.println("Yay!");
}
else
{
System.out.println("Fail!");
}
}
// be polite and close the file
inputFile.close();
}
}
You should try reading the input from a textField in an user interface(visible window) where the user puts the country and getting that as raw input shortens the code.(Only if you have a visible window on screen)
I don't have that good experience with scanners, because they tend to crash my applications when I use them. But my code for the same test does only include a scanner for the file which does not crash my application and looks like following:
Scanner inputFile = new Scanner(new File(file));
inputFile.useDelimiter("[\\r,]");
while (inputFile.hasNext()) {
String unknown = inputFile.next();
if (search.equals(unknown)) {
System.out.println("Yay!");
}
}
inputFile.close();
I think the easiest way to compare string against a file is to add a visible window where the user types the country, and reading the input to a string with String str = textField.getText();
I am guessing that your comparison is failing due to case-sensitivity.
Should your string comparison not be CASE-INSENSITIVE?
There are a few possible issues here. First, you're converting the searchString to lower case. Are the data in the CSV also lower case? If not, try using equalsIgnoreCase instead. Also, it seems to me like you should be able to match parts of the country name. In that case, equals (or equalsIgnoreCase) would only work if the user inputs the complete country name. If you want to be able to match only a part, use contains instead.

Categories

Resources