Whole text file to a String in Java

后端 未结 10 2268
遇见更好的自我
遇见更好的自我 2020-12-01 15:44

Does Java has a one line instruction to read to a text file, like what C# has?

I mean, is there something equivalent to this in Java?:

String data =          


        
10条回答
  •  误落风尘
    2020-12-01 16:04

    No external libraries needed. The content of the file will be buffered before converting to string.

      String fileContent="";
      try {
              File f = new File("path2file");
              byte[] bf = new byte[(int)f.length()];
              new FileInputStream(f).read(bf);
              fileContent = new String(bf, "UTF-8");
          } catch (FileNotFoundException e) {
              // handle file not found exception
          } catch (IOException e) {
              // handle IO-exception
          }
    

提交回复
热议问题