Avatar ·

How to read file content into a String in Java? (File to String)

Hello everyone! I'm a beginner in Java and can't figure out file reading. I need to read an entire text file into a single String to process it later (e.g., split into lines or find a substring).\n\nI tried writing it myself, but the code turns out cumbersome and doesn't work:\n\n```java\nFile file = new File("test.txt");\nString content = "";\ntry {\n FileInputStream fis = new FileInputStream(file);\n int b;\n while ((b = fis.read()) != -1) {\n content += (char) b;\n }\n fis.close();\n} catch (IOException e) {\n e.printStackTrace();\n}\nSystem.out.println(content);\n```\n\nProblems:\n1. If the file is large, the program slows down (I heard about string concatenation in a loop — it's bad).\n2. Encoding is not specified — on Windows, Russian letters turn into gibberish.\n3.