java中File类型怎么转String类型啊?

2025-04-28 23:30:29
推荐回答(5个)
回答1:

首先需要说明的而是File是io流,而你的String是数据类型,你不可能将File转成String;你可以实现的是将File的内容转换为String;你可以参考下我的java代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

 public static void main(String[] args) throws IOException {

  String fileContent = readFileContent("");
  
  System.out.println(fileContent);
 }

             //参数string为你的文件名
 private static String readFileContent(String fileName) throws IOException {

  File file = new File(fileName);
  
  BufferedReader bf = new BufferedReader(new FileReader(file));
  
  String content = "";
  StringBuilder sb = new StringBuilder();
  
  while(content != null){
   content = bf.readLine();
   
   if(content == null){
    break;
   }
   
   sb.append(content.trim());
  }
  
bf.close();
  return sb.toString();
 }
}

回答2:

转不了,但是可以通过File类对象的toString()方法获取它的默认属性值,即文件路径信息。如果还想获得更多的属性,请使用 这种形式得到你想要的内容。

回答3:

引入  Apache commons-io 的 jar包



    commons-io
    commons-io
    2.6

通过 FileUtils 工具类将文件内容转为字符串

File file = new File("myfile.txt");
try {
    String content = FileUtils.readFileToString(file);
    System.out.println("Contents of file: " + content);
} catch (IOException e) {
    e.printStackTrace();
}

回答4:

.toString();
所有的对象都能转String

回答5:

可以试试存集合,取集合
List filetostring = new ArrayList();
filetostring .add(file+"");