I am having a bit of trouble with the FileStats class to show how many lines contain the text being asked for by the user. I keep getting the incorrect answer to how many lines contain the text. I believe my code is ignoring punctuation (e.g. it won't detect the.) and upper-case variations like (The).
For Example if a file contains 5268 lines, and 1137 of those lines contain the word "the", my code returns output saying it only contains 1032 of those lines contain the word "the".
Any help would be appreciated Thank you. Code is Below
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in); //creating object for scanner class
System.out.println("Enter a filename");
String file_name = input.nextLine(); //asking user to enter a file name
int word_line_count =0, line_count=0; //count variables for counting the line count and word occurance count
String search_word = input.nextLine(); //asking user to enter a search_Word
File f = new File(file_name); //Creating File Descriptor for reading input file
String[] words_sentence = null; //creating string which stores the all words in a line
FileReader file_object = new FileReader(file_name); // Creating File Reader object
BufferedReader buffer = new BufferedReader(file_object); //Creating BufferedReader object
String sentence;
while((sentence=buffer.readLine())!=null) //Reading Content from the file till the end of file
{
if (sentence.contains(search_word))
{
word_line_count++;
}
line_count++; //increment line count for every while loop iteration
}
System.out.println(file_name + " has " + line_count + " lines"); //printing the line count
System.out.println("Enter some text");
System.out.println( word_line_count+ " line(s) contain "+"\""+search_word+"\""); //printing the number of lines contains the given word
file_object.close(); //closing file object
}
}
Related
I have an assignment where I needed to create a program that has two files, the first one stores a set of strings, then the second one stores a copy of those strings but in all uppercase.
I successfully created the program however when my professor graded my assignment, he took points off since "There was a logic error in reading ONLY one line" from this line of code:
String first_file_string = first_file_input.nextLine();
I'm not really sure what that means or how to fix it, any input or help would be much appreciated. Thank you for your time and consideration!
Here is my entire code and the line above is line 50, I'll put 3 *'s before and after the line.
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class UppercaseFileConverter
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
// file creation and writing string of characters to the file
System.out.print("Enter a file name to create the first file to read from: ");
String file_one = keyboard.nextLine();
PrintWriter outputFile_one = new PrintWriter(file_one);
System.out.print("Enter a string of characters to store in the first file: ");
String user_char = keyboard.nextLine();
outputFile_one.println(user_char);
outputFile_one.close();
System.out.printf("\nThe file: %s has been generated.\n\n", file_one);
System.out.print("Enter a file name to create the second file to write into: ");
String file_two = keyboard.nextLine();
PrintWriter outputFile_two = new PrintWriter(file_two);
outputFile_two.close();
System.out.printf("\nThe file: %s has been generated.\n", file_two);
// Opening the first file
System.out.print("\nEnter the first file name to read from: ");
String first_file = keyboard.nextLine();
// reading the first file
File open_first = new File(first_file);
if (!open_first.exists())
{ // If file doesn't exist, program ends
System.out.printf("ERROR: File, %s, cannot be found.\n", first_file);
System.out.println();
System.exit(0);
}
else
{
// accessing contents of first file
Scanner first_file_input = new Scanner(open_first);
***String first_file_string = first_file_input.nextLine();***
// opening the second file
System.out.print("\nEnter the second file name to write into: ");
String second_file = keyboard.nextLine();
// reading the second file
File open_second = new File(second_file);
if (!open_second.exists())
{ // If file doesn't exist, program ends
System.out.printf("ERROR: File, %s, cannot be found.\n", second_file);
System.out.println();
System.exit(0);
}
else
{ // storing data into the second file
String second_file_string = first_file_string.toUpperCase();
FileWriter second_fwriter = new FileWriter(open_second, true);
PrintWriter output_second = new PrintWriter(second_fwriter);
output_second.println(second_file_string);
output_second.close();
}
first_file_input.close();
System.out.printf("\nThe contents of %s has been changed to uppercase and stored in %s.\n", file_one, file_two);
System.out.println();
}
}
}
I have a program that ask the user questions and stores them into an arraylist. I want to take my text file and replace the words ending with ] with the words from my arraylist from earlier.
Here is just a piece of my code where I scanner the text file and find the words ending with ] and prints them. (Sorry if my code is a little cluttered, I'm still a bit new to java.)
//Scanning the chosen story file for story and custom words
Scanner sf = new Scanner(new File("vacation.txt"));
while (sf.hasNextLine()) {
String current = sf.nextLine();
String all_words[];
all_words = current.split(" ");
List<String> mywordList = new ArrayList<String>(all_words.length);
for (String s:all_words) {
mywordList.add( s );
}
for (String s : mywordList)
{
if (s.endsWith("]"))
System.out.print( s + " " );
So I am creating a program which when called, will have input, go to a file and change the number assigned to the string called. For example:
The file would look like:
stone 0 wood 5 water 2 metal 5
and if "wood" was called, it would go into the file, find wood then send add one to the value to the right of wood, which would only change that value to 6, then saves the file.
I've looked around on the internet but couldn't really find much which is tailored to my specific problem. Its either changing an int to either one or the other, or changing all ints to something.
public class Main {
public static void main(String[] args) {
FileWriter fw;
BufferedReader reader;
StringBuffer ib;
String allBlockAndNull = "stone 0 wood 5 water 2 metal 5";
String strDir = "C:\\Users\\amdro\\Desktop\\test.txt";
File fileDir = new File(strDir);
//creates file it doesn't exist
try {
fw = new FileWriter(fileDir);
fw.write(allBlockAndNull);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}finally {}
}
}
If you could expand from the above, that would be great!
This is a very simple and basic solution to your problem: It consists of reading the file, appending all changes to a string and overwriting the same file with the string.
Create a scanner to read your text file and initialise a new string variable
Scanner s = new Scanner(new File("fileName.txt"));
String line = "";
While there is still a character in the text file, get the word and the number
while(sc.hasNext()){
String word = s.next();
int number = s.nextInt();
Then, inside the while loop, use switch and case to check the word. For example, if word = "wood", append "wood" and the new number, newNumber to line
case "wood":
line += word + " " + newNumber + " ";
break;
The default will be appending the word and the old number, number
default:
line += word + " " + number + " ";
Finally, just create a FileWriter and a BufferedWriter to write line to the text file.
You can't add numbers to a value from a file because all the values are Strings but what you can do is replace the String value
public static void main(String[] args) throws IOException {
File file = new File("file.txt");//The file containing stone 0 wood 5 water 2 metal 5
BufferedReader reader = new BufferedReader(new FileReader(file));
String words = "", list = "";
while ((words = reader.readLine()) != null) {
list += words;
}
reader.close();
Scanner s = new Scanner(file);
if(list.contains("wood")) {
String replacedtext = list.replaceAll("wood 5", "wood 6");
FileWriter writer = new FileWriter("file.txt");
writer.write(replacedtext);
writer.close();
}
}
}
I am printing out the contents of a txt file while skipping over any numbers that are in the file.
The file I am using looks like this:
one two 3 three four
five six 7 eight
I have tried using input2.next() or input2.nextline() after System.out.print(token), but I either get an error or it doesn't read the next line accurately.
import java.util.*;
import java.io.*;
public class ScannerClass {
public static void main(String[] args) throws FileNotFoundException {
System.out.print("Enter file name and extension: ");
Scanner input = new Scanner(System.in);
File file = new File(input.next());
Scanner input2 = new Scanner(file);
String token;
//this will print out the first line in my txt file, I am having trouble
//reading the next line in the file!
while ((token = input2.findInLine("[\\p{Alpha}\\p{javaWhitespace}]+")) != null) {
System.out.print(token);
}
}
}
The output is:
one two three four
What I would like to see is the whole txt file less any numbers such as:
one two three four
five six eight
One main problem with your reg exp is that it matches only one part of the line first before the digit and then after the digit while the findInLine somehow advances the line counter.
So here is a different solution using your reg exp pattern but I have separated the reading from the file from the matching logic
Pattern p = java.util.regex.Pattern.compile("[\\p{Alpha}\\p{javaWhitespace}]+");
while (input2.hasNextLine()) {
String line = input2.nextLine();
Matcher m = p.matcher(line);
while (m.find()) {
System.out.print(m.group()); //Prints each found group
}
System.out.println();
}
You can add this RegEx;
import java.util.*;
import java.io.*;
public class ScannerClass {
public static void main(String[] args) throws FileNotFoundException {
System.out.print("Enter file name and extension: ");
Scanner reader = new Scanner(System.in);
reader = new Scanner(new File(reader.next()));
Pattern p = Pattern.compile("[a-zA-Z_]+");
Matcher m = null;
while (reader.hasNext()){
String nextLine = reader.nextLine();
m = p.matcher(nextLine);
while(m.find()) {
System.out.printf("%s ",m.group());
}
System.out.println();
}
}
}
May not be the most optimum but it'll work. Each loop iteration will split the current line into an array of strings delimited by a number (\\d+), then each array element (the alphabet words and whitespace in this case) will be streamed and joined into a single string.
while (input2.hasNextLine()) {
String[] nonNumbers = input2.nextLine().split("\\d+");
System.out.println(Arrays.stream(nonNumbers).collect(Collectors.joining()));
}
I write this code that can search for the some specific text (such as word) in the text file with scanner class, but i want also to replace (old text to the new text) in the same old text locuation.
i find in the internet that i must used replaceAll method like ( replaceAll(old, new); )
but it does't work with the scanner class.
This is my code, it just search (if it existed ) write new text in new line without change the old one.
Do i need to change the method (to get the data) form scanner to FileReader ??
File file = new File("C:\\Users....file.txt");
Scanner input = new Scanner(System.in);
System.out.println("Enter the content you want to change:");
String Uinput = input.nextLine();
System.out.println("You want to change it to:");
String Uinput2 = input.nextLine();
Scanner scanner = new Scanner(file).useDelimiter(",");
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
while (scanner.hasNextLine()) {
String lineFromFile = scanner.next();
if (lineFromFile.contains(Uinput)) {
lineFromFile = Uinput2;
writer.write(lineFromFile);
writer.close();
System.out.println("changed " + Uinput + " tO " + Uinput2);
break;
}
else if (!lineFromFile.contains(Uinput)){
System.out.println("Don't found " + Uinput);
break;
}
}
You cannot read from a file, then write to that same file. You need 2 different files.
while (read line from input file) {
if (NOT matches your search pattern)
write line to output file.
else { // matches
write start of line to your search pattern.
write your replace string
write from end of search pattern to end of line.
}
}
Unless your replace string is the same size as your search string, yes, you'll have to use 2 files. Consider the file:
Blah
Blah
Blah
Now replace the letter 'a' with "The quick Brown Fox". If you replace the first line, you've overwritten the rest of the file. Now you can't read the 2nd line, so YES, you'll have to use 2 files.
Here's another answer based on #Sedrick comment and your code.
I'm adding it to your pseudo code.
File file = new File("C:\\Users....file.txt");
Scanner input = new Scanner(System.in);
System.out.println("Enter the content you want to change:");
String Uinput = input.nextLine();
System.out.println("You want to change it to:");
String Uinput2 = input.nextLine();
Scanner scanner = new Scanner(file).useDelimiter(",");
java.util.List<String> tempStorage = new ArrayList<>();
while (scanner.hasNextLine()) {
String lineFromFile = scanner.next();
tempStorage.add(lineFromFile);
}
// close input file here
// Open your write file here (same file = overwrite).
// now loop through temp storage searching for input string.
for (String currentLine : tempStorage ) {
if (!lcurrentLine.contains(Uinput)){
String temp = currentLine.replace(Uinput, Uinput2);
write a line using temp variable
} else { // not replaced
write a line using currentLine;
}
// close write file here
By the way, you'll have to encase the reads writes with try catch to trap for IOExceptions. That's how I knew it was pseudo code. There are plenty of examples for reading/writing a file on this web site. It's easy to search for.