Search code examples
arraysscalasplitfile-read

Split contents of file into Array[String] in Scala


I have a SQL file that contains several queries. Since it is a SQL file, it has queries delimited with semicolon (;). I want to read the SQL file and have the queries as an Array[String] in Scala.

For example, I have queries.sql file that contains queries like:

select * from table1;
select col1,col2,col3 from table1 where col1 = ''
col2 = '';
select count(*) from table;

I want the output to look like this:

Array("select * from table1","select col1,col2,col3 from table1 where col1 = '' col2 =' '","select count(*) from table")

Solution

  • You might want to try this:

    import scala.io.Source
    val theArrayYouWant = Source.fromFile(<filename>).getLines.mkString.split(";")