【发布时间】:2014-03-09 23:16:31
【问题描述】:
在 Java 中将常见文件类型(.txt、.epub、.pdf)转换为字符串的最佳方法是什么?我想将此添加到我的 android 应用程序中,但我不想支付许可费。有没有好的开源库可以做到这一点?
【问题讨论】:
在 Java 中将常见文件类型(.txt、.epub、.pdf)转换为字符串的最佳方法是什么?我想将此添加到我的 android 应用程序中,但我不想支付许可费。有没有好的开源库可以做到这一点?
【问题讨论】:
【讨论】:
您不能在一个 API 中拥有所有 3 种文件格式,但我建议使用 PDF 格式
PDFBox
这是一个用于操作 PDF 文件的开源 java API ...
【讨论】:
这是一种将文本文件读入字符串的方法。它只返回原始文本。如果您想将 PDF 和其他电子书格式解释为人类可读的字符串,则需要为您要处理的每种类型找到库。
static final int BUFF_SIZE = 2048;
static final String DEFAULT_ENCODING = "utf-8";
public static String readFileToString(String filePath, String encoding) throws IOException {
if (encoding == null || encoding.length() == 0)
encoding = DEFAULT_ENCODING;
StringBuffer content = new StringBuffer();
FileInputStream fis = new FileInputStream(new File(filePath));
byte[] buffer = new byte[BUFF_SIZE];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer)) != -1)
content.append(new String(buffer, 0, bytesRead, encoding));
fis.close();
return content.toString();
}
【讨论】: