各位大大,我写了一个读txt文件的小程序,但是现在我发现他会重复的读取文件内容,不清楚为什么,请各位多多指教
代码如下:public void read(String filename )
{
FileInputStream fIn = null;
InputStreamReader isr = null;
int i=0;
char[] inputBuffer = new char[255];
String data;
File file = new File(filename);
String encoding = getFileEncode(filename);
try{
fIn=new FileInputStream(file);
isr = new InputStreamReader(fIn,encoding);
i=isr.read(inputBuffer);
data = new String(inputBuffer,0,i);
if(data!=null){
while(i!=-1){
i=isr.read(inputBuffer);
data = data+new String(inputBuffer);
}
fileread.setText(data);
}
//else
// fileread.setText(data);
}
catch (Exception e) {
e.printStackTrace();
fileread.setText("can not open the file\n");
}
finally
{
try {
isr.close();
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码如下:public void read(String filename )
{
FileInputStream fIn = null;
InputStreamReader isr = null;
int i=0;
char[] inputBuffer = new char[255];
String data;
File file = new File(filename);
String encoding = getFileEncode(filename);
try{
fIn=new FileInputStream(file);
isr = new InputStreamReader(fIn,encoding);
i=isr.read(inputBuffer);
data = new String(inputBuffer,0,i);
if(data!=null){
while(i!=-1){
i=isr.read(inputBuffer);
data = data+new String(inputBuffer);
}
fileread.setText(data);
}
//else
// fileread.setText(data);
}
catch (Exception e) {
e.printStackTrace();
fileread.setText("can not open the file\n");
}
finally
{
try {
isr.close();
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
{
FileInputStream fIn = null;
InputStreamReader isr = null;
int i=0;
char[] inputBuffer = new char[255];
String data;
File file = new File(filename);
String encoding = getFileEncode(filename);
try{
fIn=new FileInputStream(file);
isr = new InputStreamReader(fIn,encoding);
i=isr.read(inputBuffer);
data = "";
while(i!=-1){
i=isr.read(inputBuffer);
data = data+new String(inputBuffer);
}
fileread.setText(data);
}
catch (Exception e) {
e.printStackTrace();
fileread.setText("can not open the file\n");
}
finally
{
try {
isr.close();
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}楼主看看这样行不行?