Breaking a file down and rewriting it in java - 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 {
}
}
}

Related

Taking input and using it to find and read files

I've created a method which reads a file which is in the same folder as the class. I then return the text inside the file and run other methods with it.
I now need to adapt it so that the user can input a file name to be read however I am unsure on how to edit my existing code to do that. Here's what I have now.
public static String fileReader()
{
String str2 = "";
try {
Scanner sc =
new Scanner(new FileInputStream(
"C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\Untitled 2"
));
while (sc.hasNext()) {
str2 = sc.nextLine();
}
sc.close();
} catch (IOException e) {
System.out.println("No file can be found!");
}
return str2;
Any help is much appreciated!
Thanks,
Aaran
If you want to get user input use:
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
You can just pass fileName argument to fileReader() function and append it at the end of filepath.
String filePath = "C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\" + fileName;
Remember to specify extension to the file you want to open.
Scanner sc = new Scanner(new FileInputStream(filePath));
You can use Scanner class to take input from user and you can change your fileReader() to accept file name as input fileReader(String fileName).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter file name:");
System.out.println(fileReader(sc.next()));
sc.close();
}
public static String fileReader(String fileName) {
String str2 = "";
String directory = "C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\";
try {
Scanner sc = new Scanner(new FileInputStream(directory + fileName));
while (sc.hasNext()) {
str2 += sc.nextLine();
}
sc.close();
} catch (IOException e) {
System.out.println("No file can be found!");
}
return str2;
}

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());
}
}
}

Reading a file with scanner

EDIT: I ADDED A NEW PART to catch fileexception error
This is a pincheck program. I'm supposed to create a txt file with the following lines:
peter, 1212
john, 1234
mary, 0000
I then have to write a java program to prompt user for the file path of the txt file then key in their name and pin number. I'm able to compile my code but I don’t get the expected result when I type in the correct name and pin.
import java.util.*;
import java.io.*;
public class PINCheck {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter file path: ");
String filepath = s.nextLine();
File passwordFile = new File(filepath);
System.out.print("Enter name: ");
String name = s.nextLine();
System.out.print("Enter password: ");
String password = s.nextLine();
try {
Scanner sc = new Scanner(passwordFile);
while (sc.hasNext()) {
if (password.matches(".*[a-zA-Z]+.*")) {
System.out.println("You have entered a non-numerical PIN!");
} else if (sc.hasNext(name) && sc.hasNext(password)) {
System.out.println("You have logged in successfully.");
}else {
System.out.println("Login Failed.");
}
break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
This line : Scanner sc = new Scanner("passwordFile"); implies that Scanner will scan from the String specified in the constructor and not the actual file.
Use Scanner sc = new Scanner(passwordFile); instead.
A similar mistake for File passwordFile = new File("filepath");.
Use it like File passwordFile = new File(filepath);
In both cases, pass the variable, not the string.

How can I rename a file with the name of the original and delete the original file?

import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWritingApp{
public static void main(String[] args) {
String inputFilename = "marks.txt"; // It expects to find this file in the same folder as the source code
String outputFilename = "fakemarks.txt"; // The program will create this file
PrintWriter outFile;
String name,choice;
int mark1,mark2;
boolean flag=false;
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add or find a student?");
try {
outFile = new PrintWriter(new FileWriter(outputFilename),true); // create a new file object to write to
File file = new File(inputFilename); // create a file object to read from
File file1 = new File(outputFilename);
Scanner scanner = new Scanner(file); // A scanner object which will read the data from the file passed in.
choice= input.nextLine();
switch(choice){
case "f":
System.out.println("Enter a name:");
name=input.nextLine();
while (scanner.hasNextLine()) { // This will loop until there are no more lines to read
String line = scanner.nextLine();
if(line.contains(name)){
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
line=name+", " + mark1 +", "+ mark2;
outFile.println(line);
flag=true;
} else {
outFile.println(line);
}
}
if(flag==false){
System.out.println('"'+name+'"'+" wasn't found");
}
break;
case "a":
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
outFile.println(line);
}
System.out.println("Enter a name:");
name=input.nextLine();
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
outFile.println(name+", " + mark1 +", "+ mark2);
break;
}
***scanner.close();
outFile.close();
if(file1.renameTo(file)){
System.out.println("rename succesful");
} else {
System.out.println("rename unsuccesful");
}
if(file.delete()){
System.out.println("delete succesful");
} else {
System.out.println("delete unsuccesful");
}***
}catch (IOException e) {
e.printStackTrace();
}
}
}
What I am having a problem with is that every time I run the program it returns false for changing the name of the new file to the original file and deleting the original file itself. I would appreciate if someone posted some code to solve this. I have highlighted the code that outputs feedback above.

Copying from file/Writing to file

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);
}
}

Categories

Resources