-1

Should've started by saying I'm completely new at coding, this is for a final exercise in class and that I have "hit a brick wall at warp 11" on this one.

Writing a program that will read an already created file, convert content to uppercase and then create a new file and write the uppercase content to it? Here are my class and main:

import java.io.*;
import java.util.*;

public class readfile{
private Formatter z;
private Scanner x;

public void openFile(){

    try{
        x = new Scanner(new File ("week8lowercaseinput.txt"));
    }
    catch(Exception e){     
        System.out.println("Couldn't find file");           
    }
}
public void readFile(){
    while(x.hasNext()){
        String a = x.next();            
        String d = a.toUpperCase();

        System.out.printf("%s ", d);

    }
}
public void createFile(){

    try{
        z = new Formatter( new File ("WEEK8UPPERCASEOUTPUT.txt"));          
    }

    catch(Exception e){
        System.out.println("Couldn't create file.");
    }
    //z.Format("%s ", d);

}

public void closeFile(){
    x.close();
    //z.close();
}   
}

Main Class

import java.io.*;
import java.util.*;
import java.lang.*;

class TestReadFile{

public static void main(String[] args){

    readfile a = new readfile();
    a.openFile();
    a.readFile();       
    a.createFile();
    a.closeFile();

}

}

I'm able to open, read and convert content. I'm able to create a new file. The only thing that does not work is writing the converted content (uppercase) to new file. Any help would be greatly appreciated. Thank you.

rudy
  • 11
  • 1
  • In method createFile before creating Formatter call method f.createNewFile(); on creatted File instance – gauee Dec 08 '15 at 23:37
  • Can you post the code that you actually used? You have local strings which you read and convert. – ChiefTwoPencils Dec 08 '15 at 23:37
  • I see no attempt to write anything to the output file - ever... Not to mention "bad design" you open one file, create another, then `a.closeFile()` - which one is that supposed to close? just one? (which one?) both? – John3136 Dec 08 '15 at 23:42

1 Answers1

0

When you read from the file, you're just writing to the screen. You actually need to store the lines in some sort of data structure -- I'd recommend a List.

List<String> upperCaseLines = new ArrayList<>();

// inside readFile() while loop:
String line = x.next();
String uppercase = line.toUpperCase();
upperCaseLines.add(uppercase);

Then all you need to do is write the lines to file:

for(String line : upperCaseLines) {
    // write line to file
}

Also you'll want to rename your variables to things that make sense (what is x?) and your class name should start with a capital letter.

Frankly a better design would be to open both files, and write to the output file as you read from the input file.

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99