Java 如何将文件转换为字符串并将该字符串重新转换为文件
我有一个问题:“如何在Java中将文件转换为字符串并将该字符串重新转换为文件?” 我的代码:Java 如何将文件转换为字符串并将该字符串重新转换为文件,java,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
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
为空….您有许多选择,但是编写器
和读取器
界面使这一点变得简单
使用将字符串
写入文件
,如下所示:
File destination = new File("...");
String stringToWrite = "foo";
Writer writer = new FileWriter(destination);
writer.write(stringToWrite);
writer.close();
然后使用a读回:
StringBuilder appendable = new StringBuilder();
Reader reader = new FileReader(destination);
reader.read(appendable);
reader.close();
String readString = appendable.toString();
我们有一个问题:您尝试了什么?它必须保存到文件中。a)我们需要知道您需要什么(应用程序,一些源代码)B)请展开问题C)尝试FileWriter(在问题中投入精力,人们将展开答案)现在我看到了您的代码片段,似乎您将XSLX视为纯文本文件,当它们实际上是Zip存档中的XML时。在以后的问题中,我建议您在读取后暂停,将读取的数据转储回命令提示符,并检查它是否有意义。+1表示在答案上“提高标准”。可惜这是一个非常接近的问题。更令人遗憾的是,它是在编辑之前3分钟关闭的。如果不是一个好问题,那么至少有一个值得进一步关注。