下面这段代码我在一段程序中执行没有问题,但如果把它放到main中就会出问题,在循环读取的时候,中间有一段字节在new String时生成的是空串,造成整个字符串的不完整,我跟踪了一下发现这段字节中的最后一部分是半个汉字,byte的值是负数,有谁知道这是为什么 try{
StringBuffer sText = new StringBuffer("");
java.io.File xmlFile = new java.io.File("c:\\textfile.ls");
java.io.FileInputStream fis = new java.io.FileInputStream(xmlFile);
//设置文件读取缓冲,100K
byte[] readb = new byte[1024];
//读取文件内容
int iread = fis.read(readb);
if (iread > 0) {
sText.append(new String(readb, 0, iread));
}
//大于100K时循环读取
while (iread == readb.length) {
iread = fis.read(readb);
System.out.println(new String(readb, 0, iread));
sText.append(new String(readb, 0, iread));
}
System.out.println(sText.toString());
fis.close();
}catch(Exception ee){
ee.printStackTrace();
}
StringBuffer sText = new StringBuffer("");
java.io.File xmlFile = new java.io.File("c:\\textfile.ls");
java.io.FileInputStream fis = new java.io.FileInputStream(xmlFile);
//设置文件读取缓冲,100K
byte[] readb = new byte[1024];
//读取文件内容
int iread = fis.read(readb);
if (iread > 0) {
sText.append(new String(readb, 0, iread));
}
//大于100K时循环读取
while (iread == readb.length) {
iread = fis.read(readb);
System.out.println(new String(readb, 0, iread));
sText.append(new String(readb, 0, iread));
}
System.out.println(sText.toString());
fis.close();
}catch(Exception ee){
ee.printStackTrace();
}
StringBuffer sText = new StringBuffer("");
java.io.File xmlFile = new java.io.File("c:\\textfile.ls");
java.io.FileInputStream fis = new java.io.FileInputStream(xmlFile);
//设置文件读取缓冲,100K
byte[] readb = new byte[1024];
//读取文件内容
int iread = 0;
//大于100K时循环读取
while ((iread=fis.read(readb))>0) {
iread = fis.read(readb);
System.out.println(new String(readb, 0, iread));
sText.append(new String(readb, 0, iread));
}
System.out.println(sText.toString());
fis.close();
}catch(Exception ee){
ee.printStackTrace();
}
StringBuffer sText = new StringBuffer("");
java.io.File xmlFile = new java.io.File("c:\\textfile.ls");
java.io.FileInputStream fis = new java.io.FileInputStream(xmlFile);
//设置文件读取缓冲,100K
byte[] readb = new byte[1024];
//读取文件内容
int iread = 0;
//大于100K时循环读取
while ((iread=fis.read(readb))>0) {
System.out.println(new String(readb, 0, iread));
sText.append(new String(readb, 0, iread));
}
System.out.println(sText.toString());
fis.close();
}catch(Exception ee){
ee.printStackTrace();
}
try{
File f = new File("src/test.txt");
BufferedReader bi = new BufferedReader(new FileReader(f));
String line = "";
while((line=bi.readLine())!=null){
System.out.println(line);
}
}catch(Exception e){e.printStackTrace();}