java 文件与流的总结
一 java 读写文件
Java的IO操作都是基于流进行操作的,为了提高读写效率一般需要进行缓冲。
简单的示例程序如下:/**
* 读出file1中的内容,写入file2中
*
*/
BufferedReader reader=new BufferedReader(new FileReader(file1));
BufferedWriter writer=new BufferedWriter(new FileWriter(file2));
String str=null;
str=reader.readLine();
while(str!=null)
{
writer.write(str+"/r/n");
str=reader.readLine();
}
reader.close();
writer.close();
完整的示例:
import java.io.*;
public class FileReading {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("input the direction's path:");
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
try
{
String path=reader.readLine();
String fileName;
makeDir(path);
System.out.println("input the filename:");
fileName=reader.readLine();
File file=makeFile(path,fileName);
writeFile(file);
System.out.println("input the file name or the direction:");
BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
File f=new File(buff.readLine().toString());
listFile(f);
}
catch(Exception ex)
{
System.err.println(ex.getMessage());
}
}
public static void makeDir(String path)//创建目录,---文件夹
{
try
{
File file=new File(path);
if(!file.exists())
file.mkdir();
}
catch(Exception ex)
{
System.err.println(ex.getMessage());
}
}
public static File makeFile(String path,String fileName)//创建文件
{
File f=new File(path,fileName);
try
{
if(!f.exists())
f.createNewFile();
}
catch(Exception ex)
{
System.err.println(ex.getMessage());
}
finally
{
return f;
}
}
public static void writeFile(File file)//将一个文件中的内容写入另一个文件
{
try
{
if(!file.exists())
file.createNewFile();
else
{
System.out.println("input the file:");
BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
String pathname=buff.readLine();
File f=new File(pathname);
BufferedReader reader=new BufferedReader(new FileReader(f));
BufferedWriter writer=new BufferedWriter(new FileWriter(file));
String str=null;
str=reader.readLine();
while(str!=null)
{
writer.write(str+"/r/n");
str=reader.readLine();
}
reader.close();
writer.close();
}
}
catch(Exception ex)
{
System.err.println(ex.getMessage());
}
}
public static void listFile(File file)//列出所有目录及文件
{
File[] list= file.listFiles();
int filecout=0;
int dircout=0;
for(File f:list)
{
if(f.isDirectory())
{
System.out.println("this is direction "+(++dircout)+" :"+f.getName());
}
else if(f.isFile())
{
System.out.println("This is file:"+(++filecout)+" :"+f.getName());
}
}
}
}