下面是一个java中将文本转换为字符串函数 可直接调用,不过要首先获取文件的绝对路径
获取文件路径方法:File file = filechooser.getSelectedFile();
private String readTxt(String path) {
if (path == null || "".equals(path)) {
return "";
}
StringBuffer sb = new StringBuffer();
File file = new File(path);
InputStreamReader read = null;
BufferedReader reader = null;
try {
read = new InputStreamReader(new FileInputStream(file), "gb2312");
reader = new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read != null) {
try {
read.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return sb.toString();
}