源程序如下:
import java.io.*;
class Employee
{
public static void main(String[] args) throws Exception
{
RandomAccessFile raf=new RandomAccessFile("employee.txt","rw");
String str;
while((str=raf.readLine())!=null)
{
System.out.println(str);
}
}
}
出现乱码,请高手指教!
import java.io.*;
class Employee
{
public static void main(String[] args) throws Exception
{
RandomAccessFile raf=new RandomAccessFile("employee.txt","rw");
String str;
while((str=raf.readLine())!=null)
{
System.out.println(str);
}
}
}
出现乱码,请高手指教!
用BufferedReader
readLine
public final String readLine()
throws IOException
Reads the next line of text from this file. This method successively reads bytes from the file, starting at the current file pointer, until it reaches a line terminator or the end of the file. Each byte is converted into a character by taking the byte's value for the lower eight bits of the character and setting the high eight bits of the character to zero. This method does not, therefore, support the full Unicode character set.
我怀疑你的编码不一致
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>将写入文件的数据分行</title>
</head>
<body>
<%
String path=request.getRealPath(".");
RandomAccessFile rf=new RandomAccessFile(path + "\\WriteData.txt","rw");//定义一个类RandomAccessFile的对象,并实例化
rf.seek(rf.length());//将指针移动到文件末尾
rf.writeBytes("\nAppend a line to the file!");
rf.close();//关闭文件流
out.println("写入文件内容为:<br>");
FileReader fr=new FileReader(path + "\\WriteData.txt");
BufferedReader br=new BufferedReader(fr);//读取文件的BufferedRead对象
String Line=br.readLine();
while(Line!=null){
out.println(Line + "<br>");
Line=br.readLine();
}
fr.close();//关闭文件
%>
</body>
</html>
但是在你从文件中取数据的时候,建议使用BufferedReader!你可以从jdk的帮助文档中去了解RandomAccessFile!
但是在你从文件中取数据的时候,建议使用BufferedReader!你可以从jdk的帮助文档中去了解RandomAccessFile!
import java.io.*;
class Employee
{
public static void main(String[] args) throws Exception
{ BufferedReader br=new BufferedReader(new FileInputReader("employee.txt"));
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}
}
没有给出。我早已知道可以用bufferedreader读,但追加写入文件又要用
buffered writer,比较麻烦.所以我用randomaccessfile,希望大家教我怎没用
randomaccessfile读才能避免乱码
追加的时候用writeUTF()应该就不会了
{
try{
FileInputStream oFs = new FileInputStream("./employee.txt");
int nBuffer = -1;
while(-1 != (nBuffer = oFs.read()))
{
System.out.print((char)nBuffer);
}
}catch(IOException e)
{
System.out.println(e);
System.exit(1);
}
}
import java.io.*;
有汉字的话显然会乱码
然后new String(buffer),这个String的打印应该就没问题了
楼主不要用readLine(),用一个byte数组(假设是buffer)读入数据,数组长度就是raf.length()
然后new String(buffer),这个String的打印应该就没问题了
new String(buffer,"GBK");
而System.out.println(str);则是以GB2312编码把这些字符打印在屏幕上,读入和输出的编码不一致