现在有一个很小的程序,就是读取一个给定的txt文件。
我目前的状况是,txt文件如果直接通过java读取就都是乱码,除非是先用java生成一个txt文件然后再读取。
希望大家帮忙改下程序。。。
package lesson;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class c {
static String str;
static char[] charnum=new char[1024];
static int i=0;
public static void main(String[] args) {
File aFile = new File("D:/Java/example.txt");
FileInputStream inFile = null;
try {
inFile = new FileInputStream(aFile);
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel inChannel = inFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
while(inChannel.read(buf) != -1) {
str= ((ByteBuffer)(buf.flip())).asCharBuffer().toString();
System.out.println(str);
System.out.println(new String(str.getBytes(),"UTF-8"));
buf.clear();
}
inFile.close();
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}