当前位置: 代码迷 >> J2SE >> sun.io.MalformedInputException
  详细解决方案

sun.io.MalformedInputException

热度:502   发布时间:2016-04-24 17:12:36.0
◆◇◆ 怎么我能读 txt 文件,但却不能读 jpg 文件? ◆◇◆
代码如下:

String   strSourceFile   =   "D:/test.jpg ";
String   strTargetFile   =   "D:/test_copy.jpg ";

File   fileSource   =   new   File(strSourceFile);
File   fileTarget   =   new   File(strTargetFile);

int   intFileLength   =   Integer.parseInt(Long.toString(fileSource.length()));

char[]   chrFileContent   =   new   char[intFileLength];

FileReader   fileReader   =   new   FileReader(strSourceFile);

fileReader.read(chrFileContent,   0,   intFileLength);

fileReader.close();

if   (!fileTarget.exists())
{
fileTarget.createNewFile();
}

FileWriter   fileWriter   =   new   FileWriter(strTargetFile);

fileWriter.write(chrFileContent,   0,   intFileLength);

fileWriter.close();

System.out.println( "OK! ");

=====================================================

读   txt   文件的时候一切顺利,但读   jpg   文件时候却报出如下错误:

--------------------Configuration:   Test   -   JDK   version   1.4   <Default>   -   <Default> --------------------
sun.io.MalformedInputException
        at   sun.io.ByteToCharGB18030.convert(ByteToCharGB18030.java:178)
        at   sun.nio.cs.StreamDecoder$ConverterSD.convertInto(StreamDecoder.java:247)
        at   sun.nio.cs.StreamDecoder$ConverterSD.implRead(StreamDecoder.java:297)
        at   sun.nio.cs.StreamDecoder.read(StreamDecoder.java:182)
        at   java.io.InputStreamReader.read(InputStreamReader.java:167)
        at   Test.Program.CopyFile(Program.java:56)
        at   Test.Program.main(Program.java:10)
Exception   in   thread   "main "  
Process   completed.

------解决方案--------------------
Reader是用于读取字符流的!

FileReader --> FileInputStream
FileWriter --> FileoutputStream
------解决方案--------------------
这边有段 文件拷贝的 代码,你参考一下

public boolean copyfile() {
File srcFile = new File( "F:\\privateFile\\33.jpg ");
File decFile = new File( "C:\\x.jpg ");
try {

FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream ops = new FileOutputStream(decFile);
int n;
byte buff[] = new byte[1024 * 4];
decFile.createNewFile();
while ((n = fis.read(buff)) != -1) {
ops.write(buff, 0, n);

}
ops.flush();
fis.close();
ops.close();

} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException er) {
System.out.println(er);
return false;
}
return true;

}