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.
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());
}
}
}
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;
}
}
}
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.
I'm not sure how to output the reversed StringBuffer to a file, and have searched online but still been unable to determine what to do. Would appreciate any advice. I know I'm going wrong with the bwr flush at the end
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
This program reads a file with numbers, and writes the numbers to another
file, lined up in a column and followed by their total.
*/
class FileClass{
public static void main(String[] args) throws FileNotFoundException
{
// Prompt for the input and output file names
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
in.useDelimiter(""); // To recognize spaces in the text
PrintWriter out = new PrintWriter(outputFileName);
// Read the input and write the output
String s;
StringBuffer sb = new StringBuffer(s);
while (in.hasNext())
{
String input = in.next();
sb.append(input);
}
sb.reverse();
//out.printf(sb);
BufferedWriter bwr = new BufferedWriter(new FileWriter(new Filefinal.txt"));
bwr.write(sb.toString());
bwr.flush();
bwr.close();
in.close();
out.close();
}
}
I fixed up all the errors (quite a lot) you had in your coding as well:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
This program reads a file with numbers, and writes the numbers to another
file, lined up in a column and followed by their total.
*/
class FileClass{
public static void main(String[] args) throws FileNotFoundException
{
// Prompt for the input and output file names
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in;
try {
in = new Scanner(inputFile);
in.useDelimiter(""); // To recognize spaces in the text
PrintWriter out = new PrintWriter(outputFileName);
// Read the input and write the output
String s = "";
StringBuffer sb = new StringBuffer(s);
while (in.hasNext())
{
String input = in.next();
sb.append(input);
}
sb.reverse();
//out.printf(sb);
BufferedWriter bwr = new BufferedWriter(out);
// To a String.
String tmp = sb.toString();
bwr.write(tmp.toCharArray());
bwr.flush();
bwr.close();
in.close();
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
console.close();
}
}
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.