Warm tip: This article is reproduced from serverfault.com, please click

How to load a text file to a string variable in java

发布于 2020-12-06 09:35:26

I'm pretty new in the programming world, and i can't find a good explanation on how to to load a txt file to a string variable in java using eclpise.

So far, from what i have been able to understand, i am supposed to use the StdIn class, and i know that the txt file need to be located in my eclipse workspace (outside the source folder) but i don't know what excatly i need to write in the code to get the given file to load into the variable.

I could really use some help with this.

Questioner
RONOLULU
Viewed
0
Théo Louvel 2020-12-06 17:38:29

Although I'm not a Java expert, I'm pretty sure this is the information you're looking for It looks like this:

static String readFile(String path, Charset encoding)
  throws IOException
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

Basically all languages provide you with some methods to read from the file system you're in. Hope that does it for you!

Good luck with your project!