按换行符Scala拆分文件文本

时间:2017-11-06 20:13:43

标签: scala file-io numbers newline

我想从文件中读取100个以这种方式存储的数字:text file

每个号码都在不同的行上。我不确定在这里应该使用哪种数据结构,因为稍后我将需要将所有这些数字相加并提取总和的前10位数。 我只是设法简单地读取文件,但我想通过换行分隔符拆分所有文本并将每个数字作为列表或数组元素:

val lines = Source.fromFile("path").getLines.toList

如果您对此处使用的数据结构有任何建议,我将不胜感激! 方法更新:

WITH OrderedIn as (
    select ProductId Item, Date = BatchDate , Qty=StockIn, Price = PurchasePrice, ROW_NUMBER() OVER (PARTITION BY ProductId ORDER BY ProductId, [BatchDate]) as rn
    from InventoryLedgers
    where StockIn > 0
),
RunningTotals as (
    select Item, Qty, Price, CAST(Qty AS int) AS  Total, CAST(0 AS int) as PrevTotal, rn from OrderedIn where rn = 1
    union all
    select rt.Item, oi.Qty, oi.Price, CAST(rt.Total AS int)  + CAST(oi.Qty AS int), CAST(rt.Total AS int) Total, oi.rn
    from
        RunningTotals rt
            inner join
        OrderedIn oi
            on
        rt.Item = oi.Item and rt.rn = oi.rn - 1
), TotalOut as (
    select Item=ProductId, SUM(StockOut) as Qty from InventoryLedgers where StockOut>=0 group by ProductId
)
select
    rt.Item, SUM(CASE WHEN CAST(PrevTotal AS int) > out.Qty THEN rt.Qty ELSE CAST(rt.Total AS int) - out.Qty END * Price) price
from
    RunningTotals rt
        inner join
    TotalOut out
        on
            rt.Item = out.Item
where
    CAST(rt.Total AS int) > CAST(out.Qty AS int)
group by rt.Item

1 个答案:

答案 0 :(得分:1)

你几乎拥有它,只是映射到BigInt,然后你有一个BigInt列表

val lines = Source.fromFile("path").getLines.map(BigInt(_)).toList

(然后你可以使用.sum将它们全部加起来等)