Copying from file/Writing to file - java

How do you "delete" a character from a file. Also, how do you print the stuff in the file out?
Write a program that reads in a file of text, perhaps the text of a novel. The program copies the same text to an output file, except that all the useless words such as "the", "a", and "an" are removed. (Decide on what other words you with to remove. The list of words removed is called a stop list.) Do this by reading the text file token by token using hasNext() and next(), but only writing out tokens not on the stop list.
Prompt the user for the names of the input and output files. Preserve the line structure of the input file. Do this by reading each line using nextLine() and then creating a new Scanner for that line. (Look at the on-line documentation for Scanner.) With each line's Scanner, use hasNext() and next() to scan through its tokens.
public static void main(String[] args) throws IOException {
String fileName;
Scanner user = new Scanner(System.in);
System.out.print("File name: ");
fileName = user.nextLine().trim();
File file = new File(fileName);
PrintStream printfile = new PrintStream(file);
System.out.println("Input data into file: ");
String datainfile = user.nextLine();
Scanner scan = new Scanner(file);
printfile.println(datainfile);
while (scan.hasNextLine()) {
while (scan.hasNext()) {
String character = scan.next();
if (character.equals("a")) {
}
}
}
}
EDIT
thanks to peeskillet I tried attempting again. However, there seems to be an error somewhere in my program and I get:
AAApotatopotatopotatojava.util.Scanner[delimiters=\p{javaWhitespace}+][position=0] [match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
Can you inspect my program?
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Input File name: ");
String filename1 = keyboard.nextLine().trim();
System.out.print("Output File name: ");
String filename2 = keyboard.nextLine().trim();
File inputFile = new File(filename1);
File outputFile = new File(filename2);
PrintStream printfile = new PrintStream(inputFile);
System.out.println("Input data into file: ");
String datainfile = keyboard.nextLine();
printfile.println(datainfile);
Scanner inFile = new Scanner(inputFile);
PrintWriter writeFile = new PrintWriter(outputFile);
Scanner lineScanner;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String word = lineScanner.next();
if(!(word.equals("a"))) {
writeFile.print(word + " ");
System.out.print(word);
}
if(!(word.equals("an"))) {
writeFile.print(word + " ");
System.out.print(word);
}
if(!(word.equals("the"))) {
writeFile.print(word + " ");
System.out.print(word);
}
else {
writeFile.print(" ");
}
}
writeFile.println();
}
writeFile.close();
Scanner readOutput = new Scanner(outputFile);
System.out.println(readOutput);
}
}

First of all you need two File objects, one for input and one for output. You only have one.
You want to do something like this
Scanner keyboard = new Scanner(System.in);
System.out.print("Input File name: ");
String filename1 = keyboard.nextLine();
System.out.print("Output File name: ");
String filename2 = keyboard.nextLine();
File inputFile = new File(filename1);
File outputFile = new File(filename2);
Scanner infile = new Scanner(inputFile);
PrintWriter outputFile = new PrintWriter(outputFile);
Scanner lineScanner;
while(infile.hasNextLine()){ // here you read each line of a file
String line = inFile.nextLine(); // here is a line
lineScanner = new Scanner(line); // for the above line, create a scanner
// just to scan that line
while(lineScanner.hasNext()){ // loop through that line
// do something
}
}
outputFile.close();
Edit: I would just put all the conditions into one statement
while (lineScanner.hasNext()) {
String word = lineScanner.next();
if(!(word.equals("a")) && !(word.equals("an")) && !(word.equals("the"))) {
writeFile.print(word + " ");
System.out.print(word);
}
}

Related

How to change all of the letters in an input file and print them to uppercase in an output file?

I need to ask the user for an input and output file and then print all of the letters in the input file to the outputfile all uppercase.
I've tried creating different variables and messing with char
package programassignment;
import java.util.Scanner;
import java.io.*;
/**
*
* #author bambo
*/
public class ProgramAssignment {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner (System.in);
System.out.println("What is the name of the input file?");
String inputfilename=keyboard.nextLine();
File f = new File(inputfilename);
Scanner inputFile = new Scanner(f);
System.out.println("What is the name of the output file?");
String outputfile=keyboard.nextLine();
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(fw);
int lineNumber=0;
String upper = Letter.toUppercase();
while(inputFile.hasNext());
{
lineNumber++;
int letterCount = 0;
String line = inputFile.nextLine();
if (line.length () != 0)
letterCount++;
for(int i=0; i< line.length(); i++)
{
if(char.upper);
{
char.toUpperCase();
}
}
I expect the input file to print all letters to uppercase in the output file
Your code contains numerous defects, including not closing your output file; terminating your while body with a semicolon; counting lines for no discernable reason; not reading lines; not converting them to uppercase; and not writing to your output. I would use try-with-resources to ensure my resources are appropriately closed (namely the Scanner and output). I would use a PrintStream. That might look something like,
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfilename = keyboard.nextLine();
File f = new File(inputfilename);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
try (Scanner inputFile = new Scanner(f);
PrintStream ps = new PrintStream(new File(outputfile))) {
while (inputFile.hasNextLine()) {
ps.println(inputFile.nextLine().toUpperCase());
}
}
Okay, how could I have it work without using Try or Printstream?
You should be using try; but without it you would be responsible for closing your resources manually. As for using a PrintWriter instead of a PrintStream, make two calls to write; one for the line and the second for the line separator. Like,
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfilename = keyboard.nextLine();
File f = new File(inputfilename);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
pw.write(inputFile.nextLine().toUpperCase());
pw.write(System.lineSeparator());
}
pw.close();
inputFile.close();
I saw a couple of problems with your code, the main problem is that you never closed the Scanner or the File Writers. Here's my simple solution.
import java.util.*;
import java.io.*;
public class StackOverflowHelp {
public static void main(String args[])
{
Scanner keyboard = new Scanner (System.in);
System.out.println("What is the name of the input file?");
String inputfilename = keyboard.nextLine();
keyboard.close();
try
{
Scanner fileScanner = new Scanner(new File(inputfilename));
FileWriter fileOut = new FileWriter("output.txt",true);
while(fileScanner.hasNextLine())
{
String temp = fileScanner.nextLine();
temp = temp.toUpperCase();
fileOut.write(temp+"\n");
}
fileScanner.close();
fileOut.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

How can I read a file from the command line using scanner

It wont prompt the user to enter file? Please help me
public static void main (String args []){
if (0 < args.length) {
File inFile = new File(args[0]); // Make sure the file exists, can read, etc...
while (!inFile.exists()) {
Scanner console = new Scanner (inFile);
System.out.println ("Input file:"); //prompt user to input file
String inFileName = console.nextLine();
System.out.println ("Input file:"); //prompt user to input file
inFileName =inFileName.trim(); //get rid of whitespace
System.out.println(inFileName);
inFile = new File (inFileName);
}
The old way :
BufferedReader reader = new BufferedReader( new InputStreamReader( System.in)); String userInput = reader.readLine();
The new way :
Console console = System.console();
if( console != null) { String userInput = console.readLine();
For Scanner you need to use.
Scanner console = new Scanner(System.in);
I suppose you can do the expected task with few lines of code.
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Input file : ");
String inFile = userInput.next();
System.out.println("Input file is " + inFile);
}

Breaking a file down and rewriting it in java

I'm working on trying to break down this file that contains state abbreviations, state names, and zip codes. Some of the zip codes are only 3 digit zip codes and for formatting purposes have to be rewritten(Ex. 005 should be 005-005). What I need help with is separating the state names and abbreviations from the zip codes so that I can format the 3 digit zip codes into 6 digit zip codes.
The layout of the file is like this:
NY New York 005 063 090-149
etc with the rest of the states... (Notice how New York is a 2 part name and how it has a 3 digit zip code of 005 and 063. That needs to be rewritten as 005-005 and 063-063)
Here is my code:
public class ZipsReader {
public static void main(String[] args){
//Gets the file name and reads it
try {
//Prompts user for an input file
Scanner console = new Scanner(System.in);
System.out.println("Input file: ");
String inputFileName = console.next();
//Prompts user for an output file
//System.out.println("Output file: ");
//String outputFileName = console.next();
//PrintWriter out = new PrintWriter(outputFileName);
//Reads the selected file line for line
File selectedFile = new File(inputFileName);
Scanner in = new Scanner(selectedFile);
while (in.hasNextLine()) {
String line = in.nextLine();
Scanner in2 = new Scanner(line);
//Reads the selected file word for word
while (in2.hasNext()){
String state = in2.isLetter();
String word = in2.next();
if (word.matches("\\d{3}-\\d{3}")){
System.out.println(word);
}
if (word.matches("\\d{3}")){
System.out.println(word + "-" + word);
}
}
in2.close();//closes the word scanner
}
console.close();//closes the file opener scanner
in.close();//closes the line scanner
//out.close();//closes the print writer
}
//Prints out message if file cant be found
catch (FileNotFoundException e) {
System.out.println("Sorry the file could not be found.");
}
//Needed to compile
finally {
}
}
}
The .matches String method works for getting the zip codes but I am not sure how to pick out the state abbrev. and names separately from the zip codes.
Right now I am just doing it to the console for time saving reasons for the time being but I will modify it to write to another file when I get this figured out.
Thanks for the help in advance
You can try this:
public class ZipReader {
public static void main(String[] args) {
//Gets the file name and reads it
try {
//Prompts user for an input file
Scanner console = new Scanner(System.in);
System.out.println("Input file: ");
String inputFileName = "G:\\test.txt";
//Prompts user for an output file
//System.out.println("Output file: ");
//String outputFileName = console.next();
//PrintWriter out = new PrintWriter(outputFileName);
//Reads the selected file line for line
File selectedFile = new File(inputFileName);
Scanner in = new Scanner(selectedFile);
String states="";
while (in.hasNextLine()) {
String line = in.nextLine();
Scanner in2 = new Scanner(line);
//Reads the selected file word for word
while (in2.hasNext()) {
//String state = in2.isLetter();
String word = in2.next();
if (word.matches("\\d{3}-\\d{3}")) {
System.out.println(word);
}
else if (word.matches("\\d{3}")) {
System.out.println(word + "-" + word);
}
else if(word.matches("[A-Z]{2}")){
System.out.println(word);
}
else{
states=states+word+" ";
}
}
System.out.println(states+"\n");
states="";
in2.close();//closes the word scanner
}
console.close();//closes the file opener scanner
in.close();//closes the line scanner
//out.close();//closes the print writer
} //Prints out message if file cant be found
catch (FileNotFoundException e) {
System.out.println("Sorry the file could not be found.");
} //Needed to compile
finally {
}
}
}

Reading and Writing text file?

I'm suppose to write a program in which we ask the user for 2 files the first file is for reading and the second for writing
the first one we are suppose to read the file and then copy the info switch it all to uppercase and save it to the second file
I cant get it to write on the second part any help?
public class FileConverter
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the filename for the first file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner (file);
while(inputFile.hasNext())
{
String fileinfo = inputFile.nextLine();
String uppercaseinfo1 = fileinfo.toUpperCase();
}
System.out.print("Enter the filename "
+ "for the second file");
filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(file);
while(inputFile.hasNext())
{
outputFile.println();
}
}
}
You need to close() the PrintWriter
...
while(inputFile.hasNext())
{
outputFile.println();
}
ouputFile.close();
Also, You don't need two loops. Just do the transferring all in one loop. You need to make sure you have two different File objects. One for the input and one for the output. With different file names.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the filename for the first file");
String filename = keyboard.nextLine();
File file = new File(filename); // file 1
Scanner inputFile = new Scanner (file); // infile
System.out.print("Enter the filename "
+ "for the second file");
filename = keyboard.nextLine();
File file1 = new File(filename); // file 2
PrintWriter outputFile = new PrintWriter(file1); // outfile
while(inputFile.hasNext())
{
String fileinfo = inputFile.nextLine();
String uppercaseinfo1 = fileinfo.toUpperCase();
outputFile.println(uppercaeinfo1);
}
outputFile.close();
You need a FileWriter in there, and close it:
FileWriter outFile = new FileWriter(filePath);
PrintWriter out = new PrintWriter(outFile);
out.println("stuff");
out.close();
Use an instance of BufferedWriter to write into the file instead of PrintWriter.
e.g.
BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); // create the write buffer
// to-do: EITHER surround with try-catch in order catch the IO Exception OR add throws declaration
bw.write("some text"); // content for the new line
bw.newLine(); // a line break
bw.flush(); // flush the buffer and write into the file
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the filename for the first file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner (file);
System.out.print("Enter the filename "
+ "for the second file");
String filename2 = keyboard.nextLine();
File file2 = new File(filename2);
PrintWriter outputFile = new PrintWriter(file2);
while(inputFile.hasNext())
{
String fileinfo = inputFile.nextLine();
String uppercaseinfo1 = fileinfo.toUpperCase();
outputFile.println(uppercaseinfo1);
}
outputFile.close()
}
}
I do it smth like this
Not only close() method is absent. Solution has some mistakes.
// corrected statements are marked with "!"
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the filename for the first file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String uppercaseinfo1 = ""; // !
while(inputFile.hasNext())
{
String fileinfo = inputFile.nextLine();
uppercaseinfo1 += fileinfo.toUpperCase() + "\n"; // !
}
inputFile.close(); // !
System.out.print("Enter the filename "
+ "for the second file");
filename = keyboard.nextLine();
file = new File(filename); // !
PrintWriter outputFile = new PrintWriter(file);
outputFile.println(uppercaseinfo1); // !
outputFile.close(); // !
}
And, as rightly noted above, you must close input/output streams at the end, if you want changes to take effect.

Categories

Resources