0

If I have the following code:

public Bicycle(int maxSpeed, String brand, int numOfGears, String name) {

And I wanted it to read a .txt file that had 1 line of information that was as follows: "3, Huffy, 6, Charles" and return an object that contains that info - how would be the best way to do that?

Would doing the following be enough to do that?

public Bicycle(int maxSpeed, String brand, int numOfGears, String name) {
    Bicycle newBike = new Bicycle (read information from file here);
}

Please let me know if I can clarify the question any further.

1
  • 4
    This will help you. Commented Jun 24, 2015 at 23:41

2 Answers 2

1

Here is approximate code to read single line

File file = new File("test.txt");
FileReader reader = new FileReader(file);
BufferedReader buf = new BufferedReader(reader);
String line = buf.readLine();
String[] tokens = line.split(",");
int number = Integer.parseInt(tokens[0].trim());
String name = tokens[1].trim();

You will need to adjust path to text file and handle possible FileNotFoundException, also IOException for buf.readLine()buf.readLine(). Once you have string you split it. You can extract variables and use them. Be sure that data in file matches expected pattern - so additional exception handling is required. Once you got all four variables you can construct your Bicycle.

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

2 Comments

This is the right thing to go with with standard Java. You may want to name the FileReader 'fileReader' and the BufferedReader as 'bufferedReader', to avoid confusion.
You'll also probably need this in a try/catch block, for exceptions, and should look into how to close a FileReader when you're done with it.
1

You can use commons.io library

    String s = FileUtils.readFileToString(new File("{filePath}"));
    String[] words = s.trim().split(",");
    object1.setNumber(words[0]);
    object1.setName(words[1]);
    object2.setNumber(words[2]);
    object2.setName(words[3]);

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.