请教大家一个一个读取文本文件的问题!请大家多多帮忙,请进.
java中怎样依次读取多个文本文件?
我从文件夹shiyan中读取了多个文本文件的名字
File dir=new File( "f:\\gz\\shiyan ");
String filename =null;
String children[]= dir.list();
for (int i=0; i <children.length; i++) {
// Get filename of file or directory
filename = children[i];
System.out.println(filename);
}
接下来我要怎么做才能把这些文本文件里的内容写到同一个txt里?
请大家指教!
------解决方案--------------------filename = children[i];
System.out.println(filename);
BufferedReader br=new BufferedReader(new FileReader(new File( "f:\\gz\\shiyan\\ "+filename)));
String line=null;
while((line=br.read())!=null)
{
//content
}
------解决方案--------------------File dir=new File( "f:\\gz\\shiyan ");
File toFile = new File( "C:\\test.txt ");
for (File file : dir.listFiles())
{
if(file.isDirectory())
continue;
String ext = file.getName().subString(file.getName().lastIndexOf( ". ")+1);
if(!ext.equalsIgnoreCase( "txt "))
continue;
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
fis = new FileInputStream(file);
fos = new FileOutputStream(toFile, true);
int bytesRead;
byte[] buf = new byte[4 * 1024]; // 4K buffer
while ((bytesRead = fis.read(buf)) != -1)
{
fos.write(buf, 0, bytesRead);
}
fos.flush();
} catch (
IOException e)
{
throw new IOException(e.getMessage());
} finally
{
if (fos != null)
fos.close();
if (fis != null)
fis.close();
}
}