1

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.

RONOLULU
  • 727
  • 1
  • 4
  • 12

2 Answers2

3

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!

1

to read a file and store it in a String you can do it by using either String or StringBuilder:

  1. you need to define BufferedReader to with constructor of FileReader to pass the name of the file and make it ready to read from file.
  2. use StringBuilder to append every line of result to it.
  3. when the reading finished add the result to String data.
public static void main(String[] args) {
    String data = "";
    try {
        BufferedReader br = new BufferedReader(new FileReader("filename"));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        data = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36