How to import .txt file into Scala

Hi new to programming, how do I import a .txt file? My code cannot find the file, is there any specific directory where it should be placed?

My code:

object Zettel01 extends App {
import scala.io.Source

object Suchtest {
  val gesch = Source.fromFile("DieUnendlicheGeschichte.txt").getLines()
  for (w <- gesch) println(w)
}
}

      

I tried other code but the problem is always the same, I cannot find the .txt file ...

Thanks in advance for any help Flurry1337

+3


source to share


2 answers


Every Scala program that you run on your computer is ultimately a process java

. This process will have a "working directory" like every process on your computer. By default, the working directory is the working directory of the process that started it, that is, the current directory of the command line interpreter or command line when your program starts.

Now, this means that it is important to know exactly how you start your program. If you use the command line and run your program in order java MyCoolProgram

, then the current shell directory becomes the program's working directory. If you are using an IDE like Eclipse or IntelliJ IDEA, they usually use your IDE project's project folder as the working directory of the process they start.

There is an easy way to quickly find this: you can always print the result new java.io.File(".").getAbsolutePath()

. This will print the full path to the working directory. For example, you can write a small Scala program like this:

object PrintWorkingDirectory extends App {
  println(new java.io.File(".").getAbsolutePath())
}

      



and run it. On the console, you should find the full path to the program's working directory. If you place a file named "DieUnendlicheGeschichte.txt" in this directory, your program will find the file under that name.

Of course, you don't need to dump all of your files into one directory. You can create subdirectories to better organize your files. For example, you can put your file in a path like "resources / text / DieUnendlicheGeschichte.txt".

Finally, I would like to point out that there is also another way to link resource files to your program and load them. The idea is that you put code (class files) as well as resources such as text, images, CSV files, XML files, and the like in one large file. This will be the JAR file. Then you can use ClassLoader

to access the resources inside the JAR file by URL.

Explaining this process in detail is beyond the scope of this question; it just throws away a couple of keywords that you (or other readers) might be looking for if they want to find a more thoughtful process.

+2


source


System.getProperty ("user.dir") also tells you the working directory.



0


source







All Articles