I am having trouble counting the amount of words in a given text file. Every time I input a text file name, the program returns "File not found". Here is the code I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Enter File name: ");
Scanner input=new Scanner (System.in);
String fileName= input.nextLine();
FileReader wordReader;
try {
wordReader=new FileReader(fileName);
BufferedReader reader=new BufferedReader(wordReader);
String cursor;
String content="";
int numberWords=0;
while((cursor=reader.readLine()) !=null) {
String []_words=cursor.split("");
for(String w: _words)
{
numberWords++;
}
}
System.out.println("Total words: "+ numberWords);
}catch (FileNotFoundException ex) {
System.out.println("File not found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You aren't splitting correctly. Split by " " instead of ""
String []_words=cursor.split(" "); //-------------> Add Space
This will give you the words instead of individual characters.
Also, you could just print _words.length instead of looping unnecessarily.
File file = new File("sample.txt");
try(Scanner sc = new Scanner(new FileInputStream(file))){
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}
Related
My apologies for the title wording, it was hard to explain in words.
What I am trying to do I this:
I have a .txt file that has
cheese cracker salt
bread butter ham
I want the user to be able to enter 'cheese' then type in pepper which will in turn update the file to become
cheese cracker pepper
bread butter ham
I am unsure how to go about editing the third word after I have the user input the first word.
Your algorithm could look like this:
read in the file
split it up by spaces (you will get an array)
put the result into a modifiable list (you can't easily insert into an array)
search for the index of a word
insert another entry by index (you can calculate the correct index from the result of step 4)
overwrite the file with the contents of the list, separated by additional spaces.
Here is a solution utilizing File module along with BufferedReader/BufferedWriter
packages
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import java.nio.file.*;
Driver program
public class Main{
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the file name: ");
String path = sc.nextLine();
Path p = Paths.get(path);
List <String> lines = Files.readAllLines(p);
System.out.println("Enter new word:");
String newWord = sc.nextLine();
System.out.println("Which word would you like " + newWord + " to replace?");
String oldWord = sc.nextLine();
for(int i = 0; i < lines.size(); i++){
String line = lines.get(i);
line = line.replace(oldWord, word); // if current word is old word, replace with new one
lines.set(i, line); // update list
}
readFile(path); // read here will output original list
writeListToFile(lines, path); // overwrite sample.txt file
readFile(path); // read here will output updated text file from path
sc.close();
}
helper functions
public static void readFile(String fileName){
try{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null){
System.out.println(line);
line = br.readLine();
}
br.close();
}catch(IOException e){
System.out.println("Error reading file");
}
}
public static void writeListToFile(List<String> list, String path){
try{
FileWriter fw = new FileWriter(path);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < list.size(); i++){
bw.write(list.get(i));
bw.newLine();
}
bw.close();
}catch(IOException e){
System.out.println("Error writing to file");
}
}
}
I am writing a program that takes user input and displays it in a text file. I am having trouble having the input save on the file. Other similar questions have suggested to close the BufferedWriter, however I'm using a try-with-resource block which, as I understand it, should auto-close the resource. When I use fileWriter.close(); the text is saved however because it is being closed it will not be re-opened and I am given an IOException due to the stream being closed. How could I fix this issue?
Main Method
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class TextReader {
public static void main(String[] args) {
Path path = Paths.get("/Users/Coding/Desktop/myFile.txt").toAbsolutePath();
try (Scanner scan = new Scanner(System.in);
BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
Reader reader = new Reader(scan, path, fileWriter);
reader.menu();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reader Class
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
public class Reader {
Path path;
Scanner scan;
BufferedWriter fileWriter;
Reader(Scanner scan, Path path, BufferedWriter fileWriter) {
this.scan = scan;
this.path = path;
this.fileWriter = fileWriter;
}
public void menu() throws IOException {
String task;
do{
System.out.print("What would you like to do today?: ");
task = scan.nextLine();
switch(task){
case "1":
addData();
break;
case "6":
System.out.println("Goodbye!");
System.exit(0);
menu();
}
}while(!task.equals("6"));
}
void addData() throws IOException {
boolean cont = false;
do try {
System.out.print("Enter Name of Player: ");
String playerName = scan.nextLine();
System.out.print("Enter Number of Games Played: ");
int gamesPlayed = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Goals Made: ");
int goals = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Assists Made: ");
int assists = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Points Scored: ");
int points = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Saves Made: ");
int saves = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Shots Made: ");
int shotsOnGoal = Integer.parseInt(scan.nextLine());
fileWriter.write(
playerName + " " + gamesPlayed + " " + goals + " " +
assists + " " + points + " " + saves + " " + shotsOnGoal);
} catch(NumberFormatException e){
System.out.println("Enter Valid Input");
cont = true;
//insert finally clause to close fileWriter here
}while(cont);
}
}
IF fileWriter is closed in a finally clause after catching the NumberFormatException as indicated in the comment of the code, the following Exception is displayed
java.io.IOException: Stream closed
at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107)
at java.base/java.io.BufferedWriter.write(BufferedWriter.java:224)
at java.base/java.io.Writer.write(Writer.java:249)
at Reader.addData(Reader.java:74)
at Reader.menu(Reader.java:28)
at TextReader.main(TextReader.java:16)
Main
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class TextReader {
public static void main(String[] args) {
Path path = Paths.get("/Users/Coding/Desktop/myFile.txt").toAbsolutePath();
try (Scanner scan = new Scanner(System.in);
BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
Reader reader = new Reader(scan, path, fileWriter);
reader.menu();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reader Class
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
public class Reader {
Path path;
Scanner scan;
BufferedWriter fileWriter;
Reader(Scanner scan, Path path, BufferedWriter fileWriter) {
this.scan = scan;
this.path = path;
this.fileWriter = fileWriter;
}
public void menu() throws IOException {
String task;
do{
System.out.print("What would you like to do today?: ");
task = scan.nextLine();
switch(task){
case "1":
addData();
break;
case "6":
System.out.println("Goodbye!");
System.exit(0);
}
fileWriter.close();
}while(!task.equals("6"));
}
void addData() throws IOException {
boolean cont = false;
do try {
System.out.print("Enter Name of Player: ");
String playerName = scan.nextLine();
System.out.print("Enter Number of Games Played: ");
int gamesPlayed = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Goals Made: ");
int goals = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Assists Made: ");
int assists = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Points Scored: ");
int points = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Saves Made: ");
int saves = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Shots Made: ");
int shotsOnGoal = Integer.parseInt(scan.nextLine());
fileWriter.write(
playerName + " " + gamesPlayed + " " + goals + " " +
assists + " " + points + " " + saves + " " + shotsOnGoal);
cont = false;
} catch(NumberFormatException e){
System.out.println("Enter Valid Input");
cont = true;
}while(cont);
}
}
I am trying to make this program that prints out the words that start with a certain letter from a list words. For example if you enter the letter "e" it should only print words that start with the letter "e" but for some reason it is reading words like "far east" even though it does not start with the letter "e". Any suggestions?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class words {
public static void main(String[] args) throws IOException {
Scanner key = new Scanner(System.in);
File wordfile = new File("wrds.txt");
if(wordfile.exists()){
Scanner keyboard = new Scanner(wordfile);
int counter = 0;
System.out.println("Enter a character");
char wrd = key.next().charAt(0);
while(keyboard.hasNext()) {
String word = keyboard.next();
if(word.startsWith(""+ wrd)) {
counter++;
}
}
System.out.println("Found "+counter+" words that begin with "+ wrd);
}
}
}
By default, scanner breaks words with whitespaces. So 'far east' is scanned as 'far' and 'east'. Use delimiter instead to ignore whitespaces. Refer the code below.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Words {
public static void main(String[] args) throws IOException {
Scanner key = new Scanner(System.in);
File wordfile = new File("wrds.txt");
if(wordfile.exists()){
Scanner keyboard = new Scanner(wordfile);
int counter = 0;
System.out.println("Enter a charycter");
char wrd = key.next().charAt(0);
keyboard.useDelimiter(System.getProperty("line.separator"));
while(keyboard.hasNext()) {
String word = keyboard.next();
if(word.startsWith(""+ wrd)) {
counter++;
}
}
System.out.println("Found "+counter+" words that begin with "+ wrd);
}
}
}
I'm not sure how to output the reversed StringBuffer to a file, and have searched online but still been unable to determine what to do. Would appreciate any advice. I know I'm going wrong with the bwr flush at the end
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
This program reads a file with numbers, and writes the numbers to another
file, lined up in a column and followed by their total.
*/
class FileClass{
public static void main(String[] args) throws FileNotFoundException
{
// Prompt for the input and output file names
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
in.useDelimiter(""); // To recognize spaces in the text
PrintWriter out = new PrintWriter(outputFileName);
// Read the input and write the output
String s;
StringBuffer sb = new StringBuffer(s);
while (in.hasNext())
{
String input = in.next();
sb.append(input);
}
sb.reverse();
//out.printf(sb);
BufferedWriter bwr = new BufferedWriter(new FileWriter(new Filefinal.txt"));
bwr.write(sb.toString());
bwr.flush();
bwr.close();
in.close();
out.close();
}
}
I fixed up all the errors (quite a lot) you had in your coding as well:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
This program reads a file with numbers, and writes the numbers to another
file, lined up in a column and followed by their total.
*/
class FileClass{
public static void main(String[] args) throws FileNotFoundException
{
// Prompt for the input and output file names
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in;
try {
in = new Scanner(inputFile);
in.useDelimiter(""); // To recognize spaces in the text
PrintWriter out = new PrintWriter(outputFileName);
// Read the input and write the output
String s = "";
StringBuffer sb = new StringBuffer(s);
while (in.hasNext())
{
String input = in.next();
sb.append(input);
}
sb.reverse();
//out.printf(sb);
BufferedWriter bwr = new BufferedWriter(out);
// To a String.
String tmp = sb.toString();
bwr.write(tmp.toCharArray());
bwr.flush();
bwr.close();
in.close();
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
console.close();
}
}
How can I store a sentence from a file to a string, and then store the next line, which is made up of numbers, to a string?
When I use hasNextline or nextLine, none of it works. I am so confused.
Scanner kb = new Scanner(System.in);
String secretMessage = null;
String message, number = null;
File file = new File(System.in);
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext())
{
message = inputFile.nextLine();
number = inputFile.nextLine();
}
System.out.println(number + "and " + message);
You're looping over the entire file, overwriting your message and number variables, and then just printing them once at the end. Move your print statement inside the loop like this so it will print every line.
while(inputFile.hasNext())
{
message = inputFile.nextLine();
number = inputFile.nextLine();
System.out.println(number + "and " + message);
}
One suggestion I would have for reading lines from a file would be to use the Files.readAllLines() method.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Display_Summary_Text {
public static void main(String[] args)
{
String fileName = "//file_path/TestFile.txt";
try
{
List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
String eol = System.getProperty("line.separator");
for (int i = 0; i <lines.size(); i+=2)
{
System.out.println(lines.get(i).toString() + "and" + lines.get(i+1) + eol);
}
}catch(IOException io)
{
io.printStackTrace();
}
}
}
Using this set up, you can also create a stringBuilder and Writer to save the output to a file very simply if needed.