Im trying to output the console to a text file that can be created/named by the user when asked for what file the use would like to output to, but for some reason it only shows the result in the console. Is there a way to have the output be sent to a new text file INSIDE eclipse? Here's the code I have written.
Code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Project03 {
public static void main(String[] args) throws FileNotFoundException {
CaesarCipher CaesarCipher = new CaesarCipher("", 0);
Scanner choice = new Scanner(System.in);
Scanner intoff = new Scanner(System.in);
Scanner output = new Scanner(System.in);
System.out.println("Type E to encrypt a file, or D to decrypt a file");
String pick = choice.nextLine();
if (pick.toLowerCase().equals("e")) {
System.out.println("Enter the file path of the text you'd like to encrypt: ");
File file = new File(choice.nextLine());
Scanner textfile = new Scanner(file);
String line = textfile.nextLine();
System.out.println("Enter the offset you would like to use (must be 1-25)");
int offset = intoff.nextInt();
System.out.println("Name the file you would like to output to");
String TextOutput = output.nextLine();
System.out.println(CaesarCipher.encode(line, offset));
PrintStream out = new PrintStream(new FileOutputStream(TextOutput));
System.setOut(out);
} else if (pick.toLowerCase().equals("d")) {
System.out.println("Enter the file path of the text you'd like to decrypt: ");
File file = new File(choice.nextLine());
Scanner textfile = new Scanner(file);
String line = textfile.nextLine();
System.out.println("Enter the offset you would like to use (must be 1-25)");
int offset = choice.nextInt();
System.out.println("Name the file you would like to output to");
String TextOutput = output.nextLine();
System.out.println(CaesarCipher.decode(line, offset));
PrintStream out = new PrintStream(new FileOutputStream(TextOutput));
System.setOut(out);
} else {
System.out.println("Something went Wrong");
}
}
}
Here your working code
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class Project03 {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
// Don't need to bulk of Scanner object
System.out.println("Type E to encrypt a file, or D to decrypt a file");
String pick = input.nextLine();
if (pick.toLowerCase().equals("e")) {
System.out
.println("Enter the file path of the text you'd like to encrypt: ");
File file = new File(input.nextLine());
Scanner inputFromFile = new Scanner(file);
String line = inputFromFile.nextLine();
System.out
.println("Enter the offset you would like to use (must be 1-25)");
int offset = input.nextInt();
input.nextLine(); // Consume Extra NewLine
System.out.println("Name the file you would like to output to");
String textOutput = input.nextLine();
PrintStream out = new PrintStream(new FileOutputStream(textOutput));
System.setOut(out);
System.out.println(CaesarCipher.encode(line, offset)); // This line should be placed after System.setOut(out), to redirect output to the file
inputFromFile.close();
} else if (pick.toLowerCase().equals("d")) {
System.out
.println("Enter the file path of the text you'd like to decrypt: ");
File file = new File(input.nextLine());
Scanner inputFromFile = new Scanner(file);
String line = inputFromFile.nextLine();
System.out
.println("Enter the offset you would like to use (must be 1-25)");
int offset = input.nextInt();
input.nextLine(); // Consume Extra NewLine
System.out.println("Name the file you would like to output to");
String textOutput = input.nextLine();
PrintStream out = new PrintStream(new FileOutputStream(textOutput));
System.setOut(out);
System.out.println(CaesarCipher.decode(line, offset));
inputFromFile.close();
} else {
System.out.println("Something went Wrong");
}
input.close();
}
}
Some Suggestion
Follow Naming Rule
For every type of stream use one Scanner object per type.
Static method call in static way.
for some reason it only shows the result in the console
as #MadProgrammer said, you write to "System.out" before opening the "out" file, therefore, the result can't appear in the file.
System.out.println(CaesarCipher.encode(line, offset));
PrintStream out = new PrintStream(new FileOutputStream(TextOutput));
System.setOut(out);
Do you want something like this:
char[] decoded = CaesarCipher.decode(line, offset);
System.out.println(decoded);
PrintStream out = new PrintStream(new File(TextOutput));
out.print(decoded);
out.close();
Now if you really want to redirect System.out, it is another story that goes like that (but it does the same; you still have to call two "println" one for the file, the other for the console):
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class Project03 {
public static class CaesarCipher {
public CaesarCipher(String string, int i) {
}
public char[] encode(String line, int offset) {
return line.toCharArray();
}
public char[] decode(String line, int offset) {
return line.toCharArray();
}
}
public static class OutStream extends PrintStream {
PrintStream out;
public OutStream(File file, PrintStream out) throws FileNotFoundException {
super(file);
this.out = out;
}
#Override
public void println(char[] x) {
super.println(x);
out.println(x);
}
}
public static void main(String[] args) throws FileNotFoundException {
CaesarCipher CaesarCipher = new CaesarCipher("", 0);
Scanner choice = new Scanner(System.in);
Scanner intoff = new Scanner(System.in);
Scanner output = new Scanner(System.in);
System.out.println("Type E to encrypt a file, or D to decrypt a file");
String pick = choice.nextLine();
if (pick.toLowerCase().equals("e")) {
System.out.println("Enter the file path of the text you'd like to encrypt: ");
File file = new File(choice.nextLine());
Scanner textfile = new Scanner(file);
String line = textfile.nextLine();
System.out.println("Enter the offset you would like to use (must be 1-25)");
int offset = intoff.nextInt();
System.out.println("Name the file you would like to output to");
String TextOutput = output.nextLine();
OutStream out = new OutStream(new File(TextOutput), System.out);
System.setOut(out);
System.out.println(CaesarCipher.encode(line, offset));
} else if (pick.toLowerCase().equals("d")) {
System.out.println("Enter the file path of the text you'd like to decrypt: ");
File file = new File(choice.nextLine());
Scanner textfile = new Scanner(file);
String line = textfile.nextLine();
System.out.println("Enter the offset you would like to use (must be 1-25)");
int offset = choice.nextInt();
System.out.println("Name the file you would like to output to");
String TextOutput = output.nextLine();
OutStream out = new OutStream(new File(TextOutput), System.out);
System.setOut(out);
System.out.println(CaesarCipher.encode(line, offset));
} else {
System.out.println("Something went Wrong");
}
}
}
If you use more than "println" you will have to overload it in "OutStream".
I didn't touch the rest of the code in purpose.
Related
Why is PrintWriter not writing to the file in the following code?
import java.io.*;
import java.util.*;
class test{
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
System.out.println("Enter input file name");
String inputfile = in.nextLine();
System.out.println("Enter output file name");
String outputfile = in.nextLine();
in.close();
File f = new File(inputfile);
Scanner input = new Scanner(f);
PrintWriter output = new PrintWriter(outputfile);
while( input.hasNextLine()){
String s = input.nextLine(); ////// reading the file lines perfectlly
output.print(s); // but not writing
}
output.close();
input.close();
}
}
As mentioned in the code, the lines of the input files are being read but not written to the 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());
}
}
}
This is my assignment - Write a program that reads a file and removes all comma’s from it and writes it back out to a second file. It should print to the console window, at the end, the number of comma’s removed.
The program needs to:
Prompt the user for the name of the file to read.
Reads file
Write the non-comma characters to output.txt, including all spaces.
When done reading the input file, write the total number of comma’s removed to the console window.
For example, if the input file contains 3+,2 = 5m, 7%,6 =1 hello
Then the output.txt file should contain:
3+2=5m 7%6=1 hello
And the console window should print “Removed 3 commas”.
Right now I'm having trouble actually removing commas from my input file, I think I would write the line under my last if statment.
Tried figuring out how to remove commas from the input file
package pkg4.pkg4.assignment;
import java.util.Scanner;
import java.io.*;
/**
*
* #author bambo
*/
public class Assignment {
/**
* #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 inputfile?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
Scanner inputFile = new Scanner(f);
System.out.println("Please enter the output file");
String outputfile = keyboard.nextLine();
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(fw);
int lineNumber=0;
while(inputFile.hasNext());
lineNumber++;
int commacount = 0;
String line = inputFile.nextLine();
if (line.length () != 0)
commacount++;
for(int i=0; i< line.length(); i++)
{
if(line.charAt(i) == ',');
{
commacount++;
}
pw.println("removed " + commacount + "commas");
}
}
}
According to your requirement for program i am suggesting you to use java 8 classes.for simplicity.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) throws IOException {
String content = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
content = new String(Files.readAllBytes(Paths.get(inputfile)));
long total_numbers_of_char = content.chars().filter(num -> num == ',').count();
System.out.println("Please enter the output file");
content = content.replaceAll(",", "");
String outputfile = keyboard.nextLine();
Files.write(Paths.get(outputfile), content.getBytes());
System.out.println("removed " + total_numbers_of_char + " commas");
keyboard.close();
}
}
To print on console you should be using :
System.out.println("removed " + commacount + "commas");
To write the line in the output file without the commas :
pw.println(line.replaceAll(",",""));
I am working on a MabLibs project that is supposed to iterate through a file, prompt you with anything contained in a <> block and allow you to write over to a new file.
I cannot figure out how to use a Scanner to read a file and turn that into a string so I can use the .length() method to iterate a for loop through the file to find these <> blocks.
I can only use Scanner and can't use array lists, so unfortunately the for loop is the only way I can do this.
Here's the code:
import java.io.*;
import java.util.*;
public class MadLibs {
public static void main(String[] args)
throws FileNotFoundException {
intro();
madLib();
}
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.");
System.out.println();
}
public static void madLib() throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String r = input.next();
while (!(r.equalsIgnoreCase("c") || r.equalsIgnoreCase("v")
|| r.equalsIgnoreCase("q"))) {
System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
}
if (r.equalsIgnoreCase("v")) {
viewFile();
}
else if (r.equalsIgnoreCase("c")) {
createWord();
}
}
public static void createWord() throws FileNotFoundException {
System.out.println("Input file name: ");
Scanner viewFile = new Scanner(System.in);
String toRead = viewFile.nextLine();
File f = new File(toRead);
while (!f.exists()) {
System.out.println("File Not Found. Try again: ");
toRead = viewFile.nextLine();
f = new File(toRead);
}
Scanner input1 = new Scanner(new File(toRead));
String input2 = input1;
PrintStream output = new PrintStream(new File(toRead));
while (input1.hasNext()) {
String input = input1.next();
for (int i = 0; i < input2.length(); i++) {
if (input.startsWith("<") && input.endsWith(">")) {
String token = input.substring(1, input.length() - 1);
System.out.println("Please input a: " + token);
Scanner scan = new Scanner(System.in);
String replacement = scan.nextLine();
token = token.replace(token, replacement);
output.print(token);
}
}
}
}
public static void viewFile() throws FileNotFoundException {
System.out.println("Input file name: ");
Scanner viewFile = new Scanner(System.in);
String toRead = viewFile.nextLine();
File f = new File(toRead);
while (!f.exists()) {
System.out.println("File Not Found. Try again: ");
toRead = viewFile.nextLine();
f = new File(toRead);
}
Scanner input1 = new Scanner(new File(toRead));
System.out.println();
while (input1.hasNextLine()) {
System.out.println(input1.nextLine());
}
}
}
Any help is greatly appreciated.
I need to make this program for school.
It firstly prompts the user to enter in txt file, then it asks the user for a unique 3 letter code, and from the code the program will then read the txt file and return the information that is linked to that unique code.
This is what I have so far:
import java.util.*;
import java.io.*;
public class assignA
{
public static void main (String [ ] args) throws IOException
{
Scanner keyboard = new Scanner (System.in);
System.out.print("Please enter the file name");
String filename = keyboard.nextLine ();
File f = new File (filename);
Scanner fin = new Scanner (f);
while(fin.hasNextLine());
{
String line = fin.nextLine ();
}
}
I hope this helps you.
import java.util.*;
import java.io.*;
public class assignA
{
public static void main (String [ ] args) throws IOException
{
Scanner keyboard = new Scanner (System.in);
System.out.print("Please enter the file name");
String filename = keyboard.nextLine ();
File f = new File (filename);
Scanner fin = new Scanner (f);
String code = "RXP"; //You can replace it with a scanner input
while(fin.hasNextLine());
{
String line = fin.nextLine();
String[] detail = line.split("#");
if (detail[0].equals(code)) {
System.out.println(detail[1] + detail[2]);
break;
}
}
}