-1

我有一个问题:“如何在 Java 中将 File 转换为 String 并再次将该 String 取回 File?”

我的代码:

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一片空白....

4

1 回答 1

2

您有许多选择,但WriterReader接口使这变得简单。

使用 aFileWriter将您的内容写入Stringa 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();
于 2012-10-08T14:49:33.757 回答