Java i/o outputting a StringBuffer to a file - java

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

Related

Read certain words from a line of text that is chosen by the user and can be altered

My apologies for the title wording, it was hard to explain in words.
What I am trying to do I this:
I have a .txt file that has
cheese cracker salt
bread butter ham
I want the user to be able to enter 'cheese' then type in pepper which will in turn update the file to become
cheese cracker pepper
bread butter ham
I am unsure how to go about editing the third word after I have the user input the first word.
Your algorithm could look like this:
read in the file
split it up by spaces (you will get an array)
put the result into a modifiable list (you can't easily insert into an array)
search for the index of a word
insert another entry by index (you can calculate the correct index from the result of step 4)
overwrite the file with the contents of the list, separated by additional spaces.
Here is a solution utilizing File module along with BufferedReader/BufferedWriter
packages
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import java.nio.file.*;
Driver program
public class Main{
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the file name: ");
String path = sc.nextLine();
Path p = Paths.get(path);
List <String> lines = Files.readAllLines(p);
System.out.println("Enter new word:");
String newWord = sc.nextLine();
System.out.println("Which word would you like " + newWord + " to replace?");
String oldWord = sc.nextLine();
for(int i = 0; i < lines.size(); i++){
String line = lines.get(i);
line = line.replace(oldWord, word); // if current word is old word, replace with new one
lines.set(i, line); // update list
}
readFile(path); // read here will output original list
writeListToFile(lines, path); // overwrite sample.txt file
readFile(path); // read here will output updated text file from path
sc.close();
}
helper functions
public static void readFile(String fileName){
try{
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null){
System.out.println(line);
line = br.readLine();
}
br.close();
}catch(IOException e){
System.out.println("Error reading file");
}
}
public static void writeListToFile(List<String> list, String path){
try{
FileWriter fw = new FileWriter(path);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < list.size(); i++){
bw.write(list.get(i));
bw.newLine();
}
bw.close();
}catch(IOException e){
System.out.println("Error writing to file");
}
}
}

println() with Printwriter object not writing to a file

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.

How to change all of the letters in an input file and print them to uppercase in an 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());
}
}
}

Counting words from user input text file

I am having trouble counting the amount of words in a given text file. Every time I input a text file name, the program returns "File not found". Here is the code I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Enter File name: ");
Scanner input=new Scanner (System.in);
String fileName= input.nextLine();
FileReader wordReader;
try {
wordReader=new FileReader(fileName);
BufferedReader reader=new BufferedReader(wordReader);
String cursor;
String content="";
int numberWords=0;
while((cursor=reader.readLine()) !=null) {
String []_words=cursor.split("");
for(String w: _words)
{
numberWords++;
}
}
System.out.println("Total words: "+ numberWords);
}catch (FileNotFoundException ex) {
System.out.println("File not found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You aren't splitting correctly. Split by " " instead of ""
String []_words=cursor.split(" "); //-------------> Add Space
This will give you the words instead of individual characters.
Also, you could just print _words.length instead of looping unnecessarily.
File file = new File("sample.txt");
try(Scanner sc = new Scanner(new FileInputStream(file))){
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}

Java outputting console output to text file inside of eclipse

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.

Categories

Resources