Parsing a fixed-width formatted file in Java

后端 未结 10 2026
遥遥无期
遥遥无期 2020-11-28 10:51

I\'ve got a file from a vendor that has 115 fixed-width fields per line. How can I parse that file into the 115 fields so I can use them in my code?

My first thought

10条回答
  •  星月不相逢
    2020-11-28 11:10

    Most suitable for Scala, but probably you could use it in Java

    I was so fed up with the fact that there is no proper library for fixed length format that I have created my own. You can check it out here: https://github.com/atais/Fixed-Length

    A basic usage is that you create a case class and it's described as an HList (Shapeless):

    case class Employee(name: String, number: Option[Int], manager: Boolean)
    
    object Employee {
    
        import com.github.atais.util.Read._
        import cats.implicits._
        import com.github.atais.util.Write._
        import Codec._
    
        implicit val employeeCodec: Codec[Employee] = {
          fixed[String](0, 10) <<:
            fixed[Option[Int]](10, 13, Alignment.Right) <<:
            fixed[Boolean](13, 18)
        }.as[Employee]
    }
    

    And you can easily decode your lines now or encode your object:

    import Employee._
    Parser.decode[Employee](exampleString)
    Parser.encode(exampleObject)
    

提交回复
热议问题