【问题标题】:Java Applet - Convert File to StringJava Applet - 将文件转换为字符串
【发布时间】:2010-01-30 17:31:16
【问题描述】:

如何将某个文件转换成字符串?然后从那个String中获取原始文件?这需要使用Java来实现。

这将是一个很棒的代码示例或教程链接。

必须将整个文件(不是内容)转换为字符串,然后将字符串转换为文件。

谢谢。

【问题讨论】:

  • 你为什么用'applet'标记这个问题。在大多数情况下,您无法从 Applet 读取或写入文件。
  • 因为我在小程序应用程序中需要这个。
  • hm,你需要转换文件名-(to/from)-文件,还是文件contents(to/from)文件
  • 必须将整个文件(不是内容)转换为字符串,然后将字符串转换为文件。
  • 您不应该将二进制文件转换为字符串。

标签: java string file applet


【解决方案1】:

注意:在以下两种情况下,您都必须对您的小程序进行数字签名,以便授予它从文件系统读取/写入文件系统的权限!

如果您可以使用外部库,请使用Apache commons-io(您还必须对这些 jar 进行签名)

FileUtils.readFileToString(..)

FileUtils.writeStringToFile(..)

如果不能,可以看this tutorial

这适用于文本文件 - 但如果您想读取二进制文件(例如 .png),您应该将其作为字符串读取。而是将其读为byte[] 并使用commons-codec -

编码:String base64String = new String(Base64.encodeBase64(byteArray));

解码:byte[] originalBytes = Base64.decodeBase64(string.getByte());

Base64是一种用于存储二进制数据的字符串格式。

【讨论】:

  • +1 表示必须对小程序进行签名才能访问文件系统
【解决方案2】:
public static String getFileContent(File file) throws IOException
{
FileReader in=new FileReader(file);
StringWriter w= new StringWriter();
char buffer[]=new char[2048];
int n=0;
while((n=in.read(buffer))!=-1)
 {
 w.write(buffer, 0, n);
 }
w.flush();
in.close();
return w.toString();
}

public static void toFileContent(String s,File file) throws IOException
{
FileWriter f=new FileWriter(file);
f.write(s);
f.flush();
f.close();
}

【讨论】:

    猜你喜欢
    • 2012-07-19
    • 1970-01-01
    • 2020-04-26
    • 2012-04-17
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    相关资源
    最近更新 更多