I am creating a code as part of my assignment by following the following guidelines:
Write a program that will continue to prompt the user for numbers until they enter "Done" to finish, then prompts the user for a file name so that these values can be saved to that file. For example, if the user enters "output.txt", then the program should write the numbers that have been read to "output.txt".
I have gotten near the end, but I cant seem to figure out why its not processing it the way i was expecting it to. For example, this is how it looks when i run it.
Please enter number. When complete, please input 'Done':
1
Please enter number. When complete, please input 'Done':
7
Please enter number. When complete, please input 'Done':
10
Please enter number. When complete, please input 'Done':
Done
File Contents 1710
Please enter file name: Test.txt
fileName: Test.txt
I would want the numbers (file contents) to read 1 7 10 and also to create a file which it is not.
Here is my code:
package labs.lab2;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Test4 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String fileContents = "";
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter number. When complete, please input 'Done': ");
String userInput = input.nextLine();
if ("Done".equalsIgnoreCase(userInput)) {
break;
}
fileContents += userInput;
}
System.out.println("File Contents " + fileContents);
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter file name: ");
String fileName = input2.nextLine();
System.out.print("fileName: " + fileName);
//String fileNameFull = fileName + ".txt";
File file = new File(fileName);
//File file = new File(fileNameFull);
file.createNewFile();
// String fileName + ".txt";
// File file = new File(fileName + ".txt");
// file.createNewFile();
FileWriter myWriter = new FileWriter(fileName);
myWriter.write(fileContents);
myWriter.close();
you can find the absolute path of file that is created using
System.out.print("file path: "+file.getAbsolutePath());
you place this print statement after file.createNewFile();
if you find that, your file is created at this path
Other simple way it to refresh your project in IDE to find the file created in project
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();
}
}
}
So I would like to ask if there is any way to modify the code I currently have in order to make it so it only replaces certain parts of the text file.
Let's say I have a text file called TestFile1 that contains
A = Apple
B = Banana
C = Carrot
D = Durian
And another called TestFile2 which contains
A = Art
C = Clams
What I would like to happen is that the code should be able to compare the two text files and if it finds that there are two variables that match, the output file which would be TestFile3 would look like this
A = Art
B = Banana
C = Clams
D = Durian
Also, I would like to make it dynamic so that I don't have to change the code every single time that the variables are changed so it can be used for other text files.
At the moment, I currently only have this code, but what it only does is that it just fully replaces TestFile2 with TestFile1 entirely, which is not what I intend to happen.
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.charset.Charset;
import java.io.*;
import java.util.Scanner;
public class FindAndReplaceTest {
static void replaceTextFile(String fileName, String target, String replacement, String toFileName) throws IOException
{
Path path = Paths.get(fileName);
Path toPath = Paths.get(toFileName);
Charset charset = Charset.forName("UTF-8");
BufferedWriter writer = Files.newBufferedWriter(toPath, charset);
Scanner scanner = new Scanner(path, charset.name());
String line;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
line = line.replaceAll(target, replacement);
writer.write(line);
writer.newLine();
}
scanner.close();
writer.close();
}
public static void main(String[] args) throws IOException{
replaceTextFile("C:\\Users\\LS1-10\\Documents\\TestFile2.txt", "Write", "Read", "C:\\Users\\LS1-10\\Documents\\TestFile1.txt");
/*
System.out.println("Note: Make sure files to merge are in the same directory as this program!");
Scanner in = new Scanner(System.in);
String output, file1name, file2name;
System.out.print("Enter output file name: ");
output = in.nextLine();
PrintWriter pw = new PrintWriter(output + ".txt");
System.out.print("Enter name of first file: ");
file1name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader(file1name + ".txt"));
String line = br.readLine();
System.out.print("Enter name of second file: ");
file2name = in.nextLine();
br = new BufferedReader(new FileReader(file2name + ".txt"));
line = br.readLine();
pw.flush();
br.close();
pw.close();
System.out.println("Replaced variables in " + file1name + ".txt with variables in " + file2name + ".txt into " + output + ".txt"); */
}
}
I commented out the part of the psvm that would ask for user input on what the file names would be because I just took it from a previous program that I made so all I need is something that would compare the two files and make the output appear as intended. Any help would be appreciated. Thank you!
The most elegant way, given everything fits into memory would be to:
deserialize file2 to a map
upon reading file1, check if the variable has an associated value in the map, and replace if needed before outputing to file3.
import java.util.Scanner;
import java.io.*;
public class UppercaseFileConverter {
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to be read: Here is the file converted into Uppercase.");
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
//validates that the file exists
if (!file.exists()) {
System.out.println("The file " + fileName + " does not exist or could not be opened.");
System.exit(0);
}
//if file exists then reads each line and prints the upper case
else {
while (inputFile.hasNext()) {
String line = inputFile.nextLine();
System.out.println(line.toUpperCase());
}
}
inputFile.close();
System.out.println("Files read, converted and then closed.");
}
}
When I run my code, my validation that checks whether the file entered exists or not does not run but instead terminates the program. Can I use a try/catch?
You can do three things
1.Remove System.exit()
2.Add null Check before using file object
if (file!=null&&!file.exists()) {}
3.Add try catch block to handle possible exception in your case FileNotFoundException.
Please help, I need help on how to check for valid file names.
Here is part of my program...
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class BookstoreInventory
{
public static void main(String[] args)throws IOException
{
//Vaiable declartions
int edition, quanity;
double pricePerBook;
String isbn, author, title, publisherCode;
int totalQuant = 0;
double total = 0;
double totalValue = 0;
double sumOfPriceBook = 0;
//Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get the file name from the user
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
//Open the file and set delimiters
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter("_|/|\\r?\\n");
}
}
So in my program I'm not sure how I would check to see if it's a valid file. For example, when the user enters "inventory" for the name of the file this will produce an error because the filename needs the .txt so the user should have entered "inventory.txt". So is there a way to adding the .txt to the name they entered? Or how do I check to see if a file is valid? Any help would be much appreciated.
You can try this:
if (!fileName.trim().toLowerCase().endsWith(".txt")) {
fileName+= ".txt";
}
Also, if you want to know if the file already exists or not:
File file = new File(filename);
// If file doesn't exist then close application...
if (!file.exists()) { System.exist(0); }
Hope this helps.
Try concatenating the user's input string by adding .txt. It should work.
I've created a basic notepad text file (e.g., text-file.txt) and have tried placing this file in multiple file paths for my code to retrieve, but I can't seem to get this to work. Basically, I'm wanting to take the content of text-file.txt and create a second file where everything is in all caps.
Here is my code:
package abc123;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class abc123
{
public static void main (String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Please provide the name of your input file: ");
String inFileName = in.nextLine();
System.out.print("Please indicate what you'd like to name your output file: ");
String outFileName = in.nextLine();
FileReader reader = new FileReader(inFileName);
PrintWriter writer = new PrintWriter(outFileName);
Scanner fileReader = new Scanner(reader);
while(fileReader.hasNext())
{
String line = fileReader.nextLine();
line = line.toUpperCase();
writer.println(line);
}
fileReader.close();
writer.close();
System.out.println("The process is now complete. Please check your output file. Thank you.");
}
}
I'm a Java newbie, so a simple solution (and comments, as always) that I can grasp at this point would be super helpful. Thanks!
if the file isn't in the same folder as your java class, you have to give java full-path to find the file. be sure you also type the extension of the file, like ".txt".