跪求Java中写入文件和从文件中读取数据的最佳的代码!

2024-12-15 09:35:41
推荐回答(4个)
回答1:

http://keke-wanwei.javaeye.com/blog/175847JAVA读取文件和信息写入文件

回答2:

NIO操作

回答3:

/**
* 读取文本文件内容
*
* @param filePathAndName
* 带有完整绝对路径的文件名
* @param encoding
* 文本文件打开的编码方式
* @return 返回文本文件的内容
*/
public static String readTxt(String filePathAndName, String encoding)
throws IOException {
encoding = encoding.trim();
StringBuffer str = new StringBuffer("");
String st = "";
try {
FileInputStream fs = new FileInputStream(filePathAndName);
InputStreamReader isr;
if (encoding.equals("")) {
isr = new InputStreamReader(fs);
} else {
isr = new InputStreamReader(fs, encoding);
}
BufferedReader br = new BufferedReader(isr);
try {
String data = "";
while ((data = br.readLine()) != null) {
data = data.replace(data, "\r\n");
str.append(data + " ");
}
} catch (Exception e) {
str.append(e.toString());
}
st = str.toString();
} catch (IOException es) {
st = "";
}
return st;
}
/**
* 将文本内容写入文件
* @param fileName 带有完整绝对路径的文件名
* @param encoding 文本文件打开的编码方式
* @param towrite 文本内容
*/
public static void SaveStringToFile(String fileName, String towrite,String encoding) {
FileOutputStream fos = null;
OutputStreamWriter osw = null;

try {
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
file = new File(fileName);
}
fos = new FileOutputStream(file);
osw = new OutputStreamWriter(fos, encoding);

osw.write(towrite);
osw.flush();
} catch (IOException iex) {
iex.printStackTrace();
} finally {
try {
if (null != osw)
osw.close();
if (null != fos)
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

回答4:

IO 要导包