如何从文件内容创建Java字符串?

您可以使用FileInputStream类的read()方法读取文件的内容。对于此方法,您需要将字节数组作为参数,将文件的内容读取到该数组。

要将字节数组转换为Sting,只需将字节数组作为参数传递给String类的构造函数。

示例

import java.io.File;
import java.io.FileInputStream;
public class Demo {
   public static void main(String args[]) throws Exception {
     
      File file = new File("data.txt");
      FileInputStream fis = new FileInputStream(file);
      byte[] bytesArray = new byte[(int)file.length()];
      fis.read(bytesArray);
      String s = new String(bytesArray);
      System.out.println(s);
   }
}

输出结果

Krishna Kasyap