Search code examples
javaformattext-filesbufferedreader

What is the proper way to format data in a .txt file? (Java)


I would like to use a .txt file to store data for items, so I need my program to quickly iterate through the .txt file for quick comparisons to find an item in question and use the information on that item for use in the program. I'm wondering, for the sake of efficiency, what the proper way to write data into a .txt file is, and what method is best for grabbing the information. Also, is BufferedReader the best way to read a file?

(ie. How would I write this information into a .txt file? Just using Minecraft example for simplicity)...

[Block: grass, BlockData: 2, isSolid: true, etc...]

Thanks!


Solution

  • If your data is flat, you could use CSV. This way you could afterwards easily edit your data within LibreOffice or Excel.

    With flat I mean: You data class contains no Lists or Maps, just simple properties, i.e.

    class MyData {
      private TypeEnum block;
      private int blockData;
      private boolean solid;
      private String name;
    }
    

    If it contains Lists or Maps, you should consider using something like JSON or XML.

    For CSV there a several libraries out there, for example OpenCSV ( http://opencsv.sourceforge.net/ ), or you could simply use Jackson with datatype-csv ( https://github.com/FasterXML/jackson-dataformat-csv ).

    Jackson has datatype-plugins and supports lot's (!!) of formats like JSON, XML, CSV, Yaml, Protobuf, etc. pp.. Though maybe you should go with Jackson: It's pretty simple to use and there's lot of documentation, tutorials and other helpful topics on the internet.