can u help me with the coding of java, so i can copy a single file using command prompt.
so, i wanna run the java file from command prompt of windows, like "java "my java script" "my file target"" and make a copy of my "my file target" at the same directory without replace the old one.
please help me?
i came out with this
import java.io.*;
class ReadWrite {
public static void main(String args[]) throws IOException {
FileInputStream fis = new FileInputStream(args[0]);
FileOutputStream fos = new FileOutputStream("output.txt");
int n;
if(args.length != 1)
throw (new RuntimeException("Usage : java ReadWrite <filetoread> <filetowrite>"));
while((n=fis.read()) >= 0)
fos.write(n);
}
}
but the copy of the file is named as output.txt
can u guys help me with the coding, if i wanna choose my own output name?
if i type "java ReadWrite input.txt (this is the output name that i want)" on command prompt
really need help here...
import java.util.Scanner;
public class program_23{ // start of class
public static void main(String []args){ // start of main function.
Scanner input = new Scanner (System.in);
// decleration ang initialization of variables
String name = " ";
int age = 0;
int no_of_hour_work = 0;
double daily_rate = 0.0;
// get user input
System.out.print("Employee Name: ");
name = input.nextLine();
System.out.print("Employee Age: ");
age = input.nextInt();
System.out.print("No of hour(s) work: ");
no_of_hour_work = input.nextInt();
// compute for daily rate
daily_rate = no_of_hour_work * 95.75;
// display the daily rate
System.out.print("Dialy rate:"+ daily_rate);
}// end of main
}// end of class
pseudo-code:
input = open input stream for file1
output = open output stream for file 2
while (input.read() has more bytes):
write byte to output stream
close(input, output)
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();
}
}
}
https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();
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'm utterly lost in Arrays and need help...Here is the end objective of this program....
In a file called AccountArray.java, write a client program (your main method) that reads from the file called customers.txt. Read the first number in the file and create an
array of Account objects, with that number of elements. Use a “for” loop to create an Account object for each line of information you read from the file and store that into an element of the array
Here's where I am at so far... my main concern is the FileNotFound Exception Error.... I have a file named customers.txt saved in the program folder but do I need to initialize it somehow or something?
Any other input regarding things I am doing wrong in this program would be greatly accepted, I'm just beginning to learn this stuff.
public class AccountArray {
/**
* #param args
*/
public static void main(String[] args) {
List<Account> accountsArray = new ArrayList <Account>();
String name, accountnumber, balance;
Scanner diskScanner = new Scanner(new File("customers.txt"));
Scanner scanner= new Scanner ("customers.txt");
scanner.useDelimiter(" ");
int objects= scanner.nextInt();
Account[] accounts=new Account[objects];
while (objects>0){
name = scanner.nextLine();
accountnumber = scanner.nextLine();
balance = scanner.nextLine();
for(int i = 1; i < objects; i++) {
accountsArray.add(new Account(i, name, accountnumber, balance));
}
objects=objects-1;
System.out.println(name+ " " + accountnumber + " " + balance +"\n"); }// just for debugging
}
}
sample of file :
4
John Anderson
4565413
250.00
Louise Carter
2323472
1250.45
Paul Johnson
7267881
942.81
Sarah Wilson
0982377
311.26
Well, first of all, you're using the wrong Scanner object:
Scanner diskScanner = new Scanner(new File("customers.txt")); // Scans through your file --Use this one
Scanner scanner= new Scanner ("customers.txt"); // Scans through the String "customers.txt" --Not helpful
To fix the FileNotFound Exception, you need to move the file customers.txt to the folder that is output by new File("customers.txt").getAbsoultePath(); as suggested by Freaky Thommi.
You will also run into a few other errors further down, but I'll let you figure those out on your own...
Is this run form eclipse. If yes you need to have this file under your project root folder. You can always find out the absolute path by using
new File("customers.txt").getAbsoultePath();
Print this to console and see if file is present at this location
I wrote a program that asks for user input like this:
System.out.println("Where would you like the output file to end up? (full path and desired file name): ");
Scanner out_loc = new Scanner(System.in);
output_loc = out_loc.nextLine();
...
System.out.println("Hey, please write the full path of input file number " + i + "! ");
System.out.println("For example: /home/Stephanie/filein.txt");
Scanner fIn = new Scanner(System.in);
I ask several times for input in this way but it can get to be a huge pain if you mistype because then you have to kill the program and rerun. Is there an easy way to just take input all at once when you run a program? As in just declaring it in the command line when having it run?
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?
You can use file redirection.
program < file
sends the file to the standard input of the program. In your case,
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere < file
Or you can read from a file in your program. You can make this optional like
InputStream in = args.length < 1 ? System.in : new FileInputStream(args[0]);
Scanner scan = new Scanner(in); // create the scanner just once!
When you run the command as :
java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?
It runs the public static void main(String[] args) method of your primary class where you can get the userinputhere directly as:
public static void main(String[] args)
String userinputhere = args[0];
..... rest of your code
}
If there are multiple user Inputs, you can get them all as :
public static void main(String[] args)
String userinput1 = args[0];
String userinput2 = args[1];
String userinput3 = args[2];
//and so on..
..... rest of your code
}