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