Avatar ·

How to read file contents into a String in Java? (from File, InputStream, Path)

Hello everyone! I'm a beginner in Java and have been struggling with this task for two days. I need to read a text file (e.g., "data.txt") and get its contents as a single String. I tried using FileReader and BufferedReader, but I keep getting confused with try-catch, and the code ends up being huge. \n\nHere's what I wrote, but it doesn't work:\n\n```java\nFile file = new File("data.txt");\nString content = "";\ntry {\n FileReader reader = new FileReader(file);\n BufferedReader br = new BufferedReader(reader);\n String line;\n while ((line = br.readLine()) != null) {\n content += line;\n }\n br.close();\n} catch (IOException e) {\n e.printStackTrace();\n}\n```\n\nProblems:\n1. If the file is large, the code runs terribly slow (I heard that string concatenation in a loop is bad).\n2.