如何将File转换为String并再次将String转换回File

时间:2012-10-08 14:47:52

标签: java

我有一个问题:“如何将文件转换为字符串并在Java中再次将该字符串转换回文件?”

我的代码:

public static void main(String[]args) throws IOException{
    String fff = fileToString("Book.xlsx");
    byte[] bytes = fff.getBytes();

    File someFile = new File("Book2.xlsx");
    FileOutputStream fos = new FileOutputStream(someFile);
    fos.write(bytes);
    fos.flush();
    fos.close();
}

public static String fileToString(String file) {
    String result = null;
    DataInputStream in = null;

    try {
        File f = new File(file);
        byte[] buffer = new byte[(int) f.length()];
        in = new DataInputStream(new FileInputStream(f));
        in.readFully(buffer);
        result = new String(buffer);
    } catch (IOException e) {
        throw new RuntimeException("IO problem in fileToString", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) { /* ignore it */
        }
    }
    return result;
}

如何在字符串中获取Book1.xlsx并保存在book2.xlsx中? Book2.xlsx为空....

1 个答案:

答案 0 :(得分:2)

您有多种选择,但WriterReader界面使这一点变得简单。

使用FileWriterString写入File,如下所示:

File destination = new File("...");
String stringToWrite = "foo";
Writer writer = new FileWriter(destination);
writer.write(stringToWrite);
writer.close();

然后使用FileReader将其读回:

StringBuilder appendable = new StringBuilder();
Reader reader = new FileReader(destination);
reader.read(appendable);
reader.close();

String readString = appendable.toString();