Scala如何按指定起止关键字提取文本文件数据并写入新文件
Hey there! Let's figure out how to extract data by specific start/end positions and write the result to a new file in Scala. I'll break this down for you with clear examples covering two common scenarios: extracting a range of lines, and extracting character ranges from each line.
First, let's fix up your code structure
Your current code reads lines but doesn't do anything with them. We'll add logic to extract data and write it out, plus make sure resources are properly managed (no more forgetting to close files safely!).
Scenario 1: Extract a range of lines (e.g., line 3 to line 10)
If you want to grab lines between a starting line number and ending line number, here's how to do it:
import scala.io.Source import java.io.PrintWriter def extractLinesToFile(inputPath: String, outputPath: String, startLine: Int, endLine: Int): Unit = { // Use try-finally to ensure files are closed properly val source = Source.fromFile(inputPath) val writer = new PrintWriter(outputPath) try { // Convert lines to an indexed sequence (since lines are lazy, we need to materialize them) val allLines = source.getLines().toIndexedSeq // Slice from startLine-1 to endLine (since Scala uses 0-based indexing) val selectedLines = allLines.slice(startLine - 1, endLine) // Write each line to the output file selectedLines.foreach(writer.println) } finally { source.close() writer.close() } } // Usage example: extract lines 2 to 5 from file.txt and write to output.txt extractLinesToFile("file.txt", "output.txt", 2, 5)
Note: We subtract 1 from startLine because Scala's slice uses 0-based indices, while most people count lines starting at 1.
Scenario 2: Extract character ranges from each line (e.g., chars 5 to 12 of every line)
If you need to pull a specific substring from each line (based on character positions), use this approach:
import scala.io.Source import java.io.PrintWriter def extractCharsToFile(inputPath: String, outputPath: String, startChar: Int, endChar: Int): Unit = { val source = Source.fromFile(inputPath) val writer = new PrintWriter(outputPath) try { source.getLines().foreach { line => // Handle lines shorter than endChar to avoid index errors val extracted = if (line.length >= endChar) { line.substring(startChar, endChar) } else { // Optionally, handle short lines: either take the whole line or skip it line // line.isEmpty ? "" : line // alternative: skip empty lines } writer.println(extracted) } } finally { source.close() writer.close() } } // Usage example: extract characters 3 to 8 (0-based) from each line, write to output.txt extractCharsToFile("file.txt", "output.txt", 3, 8)
Important: substring in Scala uses 0-based indices, and the end index is exclusive. So substring(3,8) gives you characters at positions 3,4,5,6,7.
Bonus: Use Scala's Using for safer resource management (Scala 2.13+)
If you're on Scala 2.13 or later, you can use scala.util.Using to avoid writing try-finally blocks manually—it handles closing resources automatically:
import scala.io.Source import java.io.PrintWriter import scala.util.Using def extractLinesWithUsing(inputPath: String, outputPath: String, startLine: Int, endLine: Int): Unit = { Using(Source.fromFile(inputPath)) { source => Using(new PrintWriter(outputPath)) { writer => val selectedLines = source.getLines().toIndexedSeq.slice(startLine - 1, endLine) selectedLines.foreach(writer.println) } } }
Let me know if you meant a different kind of "start/end position"—I can adjust the solution accordingly!
内容的提问来源于stack exchange,提问作者lak

