Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
//System.out.println(filePath);
try {
FileInputStream fis = new FileInputStream(path);
FileChannel fc = fis.getChannel();
int sz = (int) fc.size();
//System.out.println(sz);
char[] chs = new char[sz];
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
CharBuffer cb = decoder.decode(bb); cb.get(chs);
webFileContent = new String(chs);
fc.close();
fis.close();
} catch (Exception e) {
System.out.println(e);
}debug是在红色地方报错,错误信息是
java.nio.charset.MalformedInputException: Input length = 1google了也没有找到有用的信息,看了jdk的api使用clear()或者reset()方法也没有效果,不知道这个是怎么使用的呢另外如果不用这个方法读,用FileInputStream读的或读出来的都是 方块块……
彻底无语了,sun咋就不能提供个直接用的接口呢
CharsetDecoder decoder = charset.newDecoder();
//System.out.println(filePath);
try {
FileInputStream fis = new FileInputStream(path);
FileChannel fc = fis.getChannel();
int sz = (int) fc.size();
//System.out.println(sz);
char[] chs = new char[sz];
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
CharBuffer cb = decoder.decode(bb); cb.get(chs);
webFileContent = new String(chs);
fc.close();
fis.close();
} catch (Exception e) {
System.out.println(e);
}debug是在红色地方报错,错误信息是
java.nio.charset.MalformedInputException: Input length = 1google了也没有找到有用的信息,看了jdk的api使用clear()或者reset()方法也没有效果,不知道这个是怎么使用的呢另外如果不用这个方法读,用FileInputStream读的或读出来的都是 方块块……
彻底无语了,sun咋就不能提供个直接用的接口呢
decode成什么了?还是原来文件的Content吗?
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder(); 然后fc.map就是分配一个缓冲区decoder.decode(bb)应该是定义缓冲区的编码方式(或者读文件的编码方式)
* Checked exception thrown when an input byte sequence is not legal for given
* charset, or an input character sequence is not a legal sixteen-bit Unicode
* sequence.
*
* @since 1.4
*/public class MalformedInputException===========================================是否你的源文件不是以UTF-8编码?
import java.io.FileInputStream;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
public class FielTest {
public static void main(String[] args){
FielTest ft=new FielTest();
ft.test();
}
public void test(){
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
try {
FileInputStream fis = new FileInputStream("D:\\dao.properties");
FileChannel fc = fis.getChannel();
int sz = (int) fc.size();
char[] chs = new char[sz];
// 将此通道的文件区域直接映射到内存中。
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
//decode(ByteBuffer in)
//把单个输入字节缓冲区的剩余内容解码到新分配的字符缓冲区的便捷方法。
CharBuffer cb = decoder.decode(bb);
System.out.println(cb.toString());
//cb.get(chs);
fc.close();
fis.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
运行结果:
url=jdbc:oracle:thin:@localhost:1521:xe
name=system
password=wazgrmjfjpp
driver=oracle.jdbc.driver.OracleDriver