简体   繁体   中英

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

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.

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!

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM