

java读取txt文件的乱码问题
在实际工作中,经常会遇到读取和写入文件时乱码的问题。这其实主要是因为txt文件的保存默认编码是ANSI,可以人为的将其设定为UTF-8(将txt文件另存为的时候可以看到有个编码下拉框)。下面是我在实际工作中遇到的一个问题,需要按行读取/写入一个特定的txt文件,这个txt文件只有4行。.文件的读取和写入可以采用如下方法:
package readandwrite;
import java.io.*;
public class RWFile {
public String[] ReadFile(String RealPath) throws FileNotFoundException,
UnsupportedEncodingException, IOException {
File rf = new File(RealPath + "link.txt");
InputStreamReader read = new InputStreamReader(new FileInputStream(rf),
"utf-8");
BufferedReader reader = new BufferedReader(read);
String line = new String();
String sLine[] = new String[4];
int i = 0;
while ( (line = reader.readLine()) != null&&(i<4)) {
sLine[i] = line.substring(5, line.length());
// sLine[i]=line;
System.out.println(sLine[i]);
i++;
}
reader.close();
read.close();
return sLine;
}
public void WriteFile(String[] w,String RealPath) throws IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream(RealPath + "\\link.txt"));
int i =0;
while(i<w.length){
pw.write("&bt"+i+"="+w[i]+"\n");
i++;}
}
}
这里的RealPath我是通过request.getRealPath("\")方法得到的(这个方法已经不提倡使用了,当由于兼容性的问题,java还保留了这个方法),针对不同的中间件和OS得到的绝对路径不同,在使用时需要注意。
小弟初入java世界,文章如有不严谨和不正确的地方,请大家多多指点。如有更好的解决方法请大家不要保留一定要告诉我啊(o^^o)--------风过无痕
本站地址:http://www.bajiao123.com

