Reading a line from a text file and splitting its contents

  • I have this kind of file structure


    Where I would want to identify the gender and age of person, <Gender>:<Name>:<age>

    BufferedReader in = new BufferedReader(new FileReader("people.ser"));
    String s;

    while((s = in.readLine()) != null){

    String[] var = s.split(":");
    //var[0]=MALE etc etc

    }catch(Exception e){

    • Is using a delimiter (like a : in this case) to split string considered a bad practice?

    • What about using the array from the splitted string to store it in some place?

    • Are there any alternatives and better file structure?

    String.split(RegEx) is the now recommended for new Java'versions (StringTokenizer for old version compatibility). With 'palacsint' advices, you code look fine.

  • palacsint

    palacsint Correct answer

    9 years ago

    I don't think that using : is a bad practice but you have to escape it somehow if it occurs inside your data. Anyway, I'd consider using XML or JSON here.

    Some notes about the code:

    1. You should close the stream (in a finally block). See Guideline 1-2: Release resources in all cases in Secure Coding Guidelines for the Java Programming Language

    2. The .ser file extension is often used for serialized Java objects. I'd use something else to avoid the possible confusion.

    3. It's a good practice to set the character set when you read a text file. The used FileReader always uses the default charset which could vary from system to system. Consider using InputStreamReader and FileInputStream as the documentation of FileReader says. Here is an example:

      FileInputStream fileInputStream = null;
      InputStreamReader inputStreamReader = null;
      BufferedReader bufferedReader = null;
      try {
      fileInputStream = new FileInputStream("people.dat");
      inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
      bufferedReader = new BufferedReader(inputStreamReader);

      // use BufferedReader here
      } finally {

      It uses IOUtils from Apache Commons IO and closes the FileInputStream even if the constructor of InputStreamReader or BufferedReader throws an exception.

    How would I do number 3?

    @KyelJmD: See the edit, please.

    why did you use final?

    @KyelJmD: `final` helps readers and maintainers, because they know that the reference always points to the same instance and it doesn't change later. but you can find other questions on Programmers.SE in the topic.

    I would place those final variables in the class? or inside a method that calls them?

    @KyelJmD: I've added a more detailed example.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM