Reading and Writing text file? - java

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.

Related

Taking input and using it to find and read files

I've created a method which reads a file which is in the same folder as the class. I then return the text inside the file and run other methods with it.
I now need to adapt it so that the user can input a file name to be read however I am unsure on how to edit my existing code to do that. Here's what I have now.
public static String fileReader()
{
String str2 = "";
try {
Scanner sc =
new Scanner(new FileInputStream(
"C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\Untitled 2"
));
while (sc.hasNext()) {
str2 = sc.nextLine();
}
sc.close();
} catch (IOException e) {
System.out.println("No file can be found!");
}
return str2;
Any help is much appreciated!
Thanks,
Aaran
If you want to get user input use:
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
You can just pass fileName argument to fileReader() function and append it at the end of filepath.
String filePath = "C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\" + fileName;
Remember to specify extension to the file you want to open.
Scanner sc = new Scanner(new FileInputStream(filePath));
You can use Scanner class to take input from user and you can change your fileReader() to accept file name as input fileReader(String fileName).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter file name:");
System.out.println(fileReader(sc.next()));
sc.close();
}
public static String fileReader(String fileName) {
String str2 = "";
String directory = "C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\";
try {
Scanner sc = new Scanner(new FileInputStream(directory + fileName));
while (sc.hasNext()) {
str2 += sc.nextLine();
}
sc.close();
} catch (IOException e) {
System.out.println("No file can be found!");
}
return str2;
}

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

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

Copying from file/Writing to file

How do you "delete" a character from a file. Also, how do you print the stuff in the file out?
Write a program that reads in a file of text, perhaps the text of a novel. The program copies the same text to an output file, except that all the useless words such as "the", "a", and "an" are removed. (Decide on what other words you with to remove. The list of words removed is called a stop list.) Do this by reading the text file token by token using hasNext() and next(), but only writing out tokens not on the stop list.
Prompt the user for the names of the input and output files. Preserve the line structure of the input file. Do this by reading each line using nextLine() and then creating a new Scanner for that line. (Look at the on-line documentation for Scanner.) With each line's Scanner, use hasNext() and next() to scan through its tokens.
public static void main(String[] args) throws IOException {
String fileName;
Scanner user = new Scanner(System.in);
System.out.print("File name: ");
fileName = user.nextLine().trim();
File file = new File(fileName);
PrintStream printfile = new PrintStream(file);
System.out.println("Input data into file: ");
String datainfile = user.nextLine();
Scanner scan = new Scanner(file);
printfile.println(datainfile);
while (scan.hasNextLine()) {
while (scan.hasNext()) {
String character = scan.next();
if (character.equals("a")) {
}
}
}
}
EDIT
thanks to peeskillet I tried attempting again. However, there seems to be an error somewhere in my program and I get:
AAApotatopotatopotatojava.util.Scanner[delimiters=\p{javaWhitespace}+][position=0] [match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
Can you inspect my program?
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Input File name: ");
String filename1 = keyboard.nextLine().trim();
System.out.print("Output File name: ");
String filename2 = keyboard.nextLine().trim();
File inputFile = new File(filename1);
File outputFile = new File(filename2);
PrintStream printfile = new PrintStream(inputFile);
System.out.println("Input data into file: ");
String datainfile = keyboard.nextLine();
printfile.println(datainfile);
Scanner inFile = new Scanner(inputFile);
PrintWriter writeFile = new PrintWriter(outputFile);
Scanner lineScanner;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String word = lineScanner.next();
if(!(word.equals("a"))) {
writeFile.print(word + " ");
System.out.print(word);
}
if(!(word.equals("an"))) {
writeFile.print(word + " ");
System.out.print(word);
}
if(!(word.equals("the"))) {
writeFile.print(word + " ");
System.out.print(word);
}
else {
writeFile.print(" ");
}
}
writeFile.println();
}
writeFile.close();
Scanner readOutput = new Scanner(outputFile);
System.out.println(readOutput);
}
}
First of all you need two File objects, one for input and one for output. You only have one.
You want to do something like this
Scanner keyboard = new Scanner(System.in);
System.out.print("Input File name: ");
String filename1 = keyboard.nextLine();
System.out.print("Output File name: ");
String filename2 = keyboard.nextLine();
File inputFile = new File(filename1);
File outputFile = new File(filename2);
Scanner infile = new Scanner(inputFile);
PrintWriter outputFile = new PrintWriter(outputFile);
Scanner lineScanner;
while(infile.hasNextLine()){ // here you read each line of a file
String line = inFile.nextLine(); // here is a line
lineScanner = new Scanner(line); // for the above line, create a scanner
// just to scan that line
while(lineScanner.hasNext()){ // loop through that line
// do something
}
}
outputFile.close();
Edit: I would just put all the conditions into one statement
while (lineScanner.hasNext()) {
String word = lineScanner.next();
if(!(word.equals("a")) && !(word.equals("an")) && !(word.equals("the"))) {
writeFile.print(word + " ");
System.out.print(word);
}
}

Categories

Resources