Scala程序抛出java.io.FileNotFoundException问题求助
Hey there, let's work through this FileNotFoundException issue together—even though you confirmed the file exists, there are a few common Windows-specific gotchas that might be tripping you up. Here are the fixes to try, in order of likelihood:
1. Fix the Path Separator
While three forward slashes /// should work in theory, Windows handles file paths more reliably with either:
- Single forward slashes:
C:/DataResearch/SparkScala/MN212142_9392.csv - Double backslashes (since backslashes are escape characters in Scala strings):
C:\\DataResearch\\SparkScala\\MN212142_9392.csv
Updating your path to one of these formats is the most common quick fix for Windows path issues in Scala.
2. Run Your IDE with Administrator Permissions
Folders directly under the C: drive often require elevated permissions to access. If you're running IntelliJ IDEA as a regular user, it might not have permission to read from C:\DataResearch.
Fix: Right-click your IntelliJ shortcut and select Run as administrator, then re-run your code.
3. Verify the File Name Isn't Hiding an Extra Extension
Windows defaults to hiding file extensions for known types. That means your file might actually be named MN212142_9392.csv.csv (the second .csv is hidden, so you only see the first part in File Explorer).
Fix: Open File Explorer, go to the View tab, and check the File name extensions box. Double-check that your file's full name matches exactly what's in your code.
4. Double-Check for Typos
It sounds trivial, but even a tiny typo in the folder or file name will trigger this error. Confirm:
DataResearchandSparkScalaare spelled correctly in both your code and the file system- The filename
MN212142_9392.csvmatches exactly (Windows is case-insensitive, but aligning case avoids edge cases)
Modified Code Example
Here's your code updated with a single-forward-slash path (the simplest reliable format for Windows):
import scala.io.Source case class TempData(day:Int , DayOfYear:Int , month:Int , year:Int , precip:Double , snow:Double , tave:Double, tmax:Double, tmin:Double) object TempData { def main(args:Array[String]) : Unit ={ val source = Source.fromFile("C:/DataResearch/SparkScala/MN212142_9392.csv") val lines = source.getLines().drop(1) val data= lines.map{ line => val p = line.split(",") TempData(p(0).toInt , p(1).toInt, p(2).toInt, p(4).toInt , p(5).toDouble, p(6).toDouble , p(7).toDouble, p(8).toDouble,p(9).toDouble) }.toArray source.close() data.take(5).foreach(println) } }
Start with the first two fixes—they resolve 90% of these Windows file access issues. If none of these work, we can dig into more edge cases!
内容的提问来源于stack exchange,提问作者Harshit Kakkar

