我有一个问题:“如何将文件转换为字符串并在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
为空....
答案 0 :(得分:2)
您有多种选择,但Writer
和Reader
界面使这一点变得简单。
使用FileWriter
将String
写入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();