0

Hello I have a working program that reads a txt file (name, id, email, password) and writes only name and email to an output file of .html extension...

my trouble is I have the program working all under 1 class.. but my requirements is I need multiple classes.. 1 for processing, 1 for reading, 1 for writing. How would you recommend I break up my file? Im kind of confused and any guidance is appreciated Thank you

import java.io.*;

public class test {

public static void main(String[] args) throws Exception{
    // define the path to your text file

    System.out.println("Enter your file name \n");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String myFilePath = in.readLine();
    String file1 = (myFilePath + ".txt");     
    System.setOut(new PrintStream(new FileOutputStream(myFilePath + ".html")));
    // read and parse the file
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(file1)));
        String line, name, email;
        // read through the first two lines to get to the data
        line = br.readLine();
        line = br.readLine();
        while ((line = br.readLine()) != null) {
            if (line.contains("|")) {
                // do line by line parsing here
                line = line.trim();
                // split the line
                String[] parts = line.split("[|]");
                // parse out the name and email
                name = parts[1].trim();
                email = parts[2].trim();
                // rearrange the name
                String[] nParts = name.split("  *");
                if (nParts.length == 3) {
                    name = nParts[1] + " " + nParts[2] + " " + nParts[0];
                } else {
                    name = nParts[1] + " " + nParts[0];
                }
                // all done now, let's print the name and email
                System.out.println(email + " " + name);
            }
        }
        br.close();
    } catch (Exception e) {
        System.out.println("There was an issue parsing the file.");
    }
}
}
1
  • create a class for each of them; each class having a corresponding method. Then create objects of that class in main method and call methods sequentially.... Commented Feb 25, 2014 at 3:46

4 Answers 4

2

What you're looking for is logical separation between components. The rule of thumb is:

"If tomorrow I write another program, will I be able to reuse some of this code?"

For this case, think about the different pieces in your program:

  1. Dealing with files - create utility functions for reading/writing files. Writing to an output stream directly is a design idea than redirecting System.out and writing using System.out.println (Tomorrow you may want to write to multiple output streams). This is also the place to handle errors.

  2. Processing String data - split, trim, concatenate, etc. You can write a function that takes a string input and outputs a new processed String according to the requirements. (tomorrow input will come from the web rather than a filesystem).

  3. A file with a main function that calls functions on the other 2 files and wraps the process.

Sign up to request clarification or add additional context in comments.

Comments

0

@Ariel T beat me to it.

To be honest, you can approach this from a number of different ways.

Given that and the fact that you've got all of the code that you need, I thought I'll merely provide a framework for how I would approach it.

/*
* Class Responsibility: read the file content and return it as a something usable
*/ 
class MyFileReader {
    public List<String> read(String filename) {
        /*
         * 1. open a file for reading
         * 2. read each line and add it to a list
         * 3. return the list (represents our file content)
         */
    }
}

/*
* Class Responsibility: take the content which we read from a file and turn it 
*   into usable Java objects 
*/
class MyFileProcessor {
    public List<Info> process(List<String> linesFromFile) {
        /*
         * 1. for each string (that represents a line from the input file)
         * 2. split it into identifiable parts
         * 3. create a new object to hold each of these parts  
         * 4. add that object to a list
         * 5. return the list
         */
    }
}

/*
 * Class Responsibility: write the java objects to a file 
 *  Note*: this is much easier if you override the toString method for your 
 *          info object
 */
class MyFileWriter {
    public void writeToFile(List<Info> infoObjects, String filename) {
        /*
         * 1. open a file using the filename for writing
         * 2. write some content
         * 3. close file
         */
    }
}

/*
 * Class Responsibility: hold the values that we care about
 */
class Info {
    private String name;
    private int id;
    private String email;
    private String password;

    public Info(String name, int id, String email, String password) {
        this.name = name;
        this.id = id;
        this.email = email;
        this.password = password;
    }

    /*
     * ... getters and setters
     */
}

EDIT:

main() stays right where it is. Actually, it's main() that will be using your classes after their constructed!

Check it out: We'll read the file, modify an object, then write those objects back to a file.

public class Main {
    public static void main(String[] args) {
        MyFileReader fileReader = new MyFileReader();
        MyFileProcessor fileProcessor = new MyFileProcessor();
        MyFileWriter fileWriter = new MyFileWriter();

        List<String> lines = fileReader.read("input-file.txt");
        List<Info> fileContentAsObjects = fileProcessor.process(lines);

        if (fileContentAsObjects.size() > 0)
        {
            Info singleInfo = fileContentAsObjects.get(0);
            System.out.println(singleInfo);             //if you've overridden toString() ;)

            singleInfo.setName("changedName");          // modify it

            fileContentAsObjects.remove(0);             // get rid of the old one
            fileContentAsObjects.insert(0, singleInfo); // replace it with the same updated one

            fileWriter.write(fileContentAsObjects);     // writes updated info object to file
        }
    }
}

1 Comment

thanks bro you got the juice.. where do you suggest my main() goes?
0

JAVA doesn't have partial classes like C# does. You can do almost the same thing by using aggregation, delegation, and abstract base classes.

Comments

0

Make classes for those portions of code which are reusable (in future). So file read, write, and the business logic for processing content of file. Thus your code should be separated in three different classes with appropriate methods in them. As Justin Said. And The main() method will be in a new Test class which will create objects of three above class and call methods from them for respective tasks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.