下面这段代码我在一段程序中执行没有问题,但如果把它放到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();
}
解决方案 »
- 如何获得文件的类型
- ~~~~~~~~~~~~~~~~~请大家帮我优化开启线程的思路~~~~~~~~~~~~~
- 用什么方法能获得按钮上的文本?
- UltraEdit用于调试java,Ctrl+Shift+0快捷键被输入法占用了,如何改变javac等命令的快捷键?
- 高手们!sos!!!
- 急!一个jpcap抓包获取http包中url的小程序出现问题,求大神帮忙
- 如何从数据库中取出最后一行的主键?
- 终于可以用JAVA支持手机短信发送、接收了,高兴散粉!!!
- 在那可以订阅java的新闻组?
- 谁有java多线程方面的资料文档或网址?
- 为什么输出结果是:12aa66
- ANSI_CHARSET 跟SYMBOL_CHARSET的含义?
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();}