Java -- IO

1. 文件过滤器

public class Main {

	public static void main(String[] args) throws IOException 
	{
		File file = new File("/home/test/");
		String [] nameList = file.list(new FilenameFilter() {   //文件过滤器	
			@Override
			public boolean accept(File dir, String name) {
				// TODO Auto-generated method stub				
				return name.endsWith(".png")  
						|| new File(name).isDirectory();  //后缀名"png", 或者是目录
			}
		});
		
		for(String str : nameList )
		{
			System.out.println(str);
		}		
	}
}

2. 整理

// * write by kevin, 2013/7/8
 
import java.io.*;


public class IO_test {
 
 public boolean IsExist(String fileName){ //文件是否存在
  File file = new File(fileName);
  if( file.exists() ){
   System.out.println("Is file: " + file.isFile());
   System.out.println("Filename is: " + file.getName());
   System.out.println("Path is: " + file.getPath());
   System.out.println("AbsolutePath " + file.getAbsolutePath());
   System.out.println("Parent dir is: " + file.getParent());
   System.out.println("File size is: " + file.length() + " bytes");
   return true;
  }
  else{
   return false;
  }  
 }
 
 public boolean CreateFile(String fileName) throws IOException{ //创建文件  
  File file = new File(fileName);  
  if( file.exists() ){
   System.out.println(fileName + " File has existed");
   return false;
  }
  else{
   file.createNewFile();   
   return true;
  }  
 }
 
 public boolean CreateDir(String dirName){ //创建目录
  File file = new File(dirName);
  if( file.exists() ){
   System.out.println(dirName + " Dir has existed");
   return false;
  }
  else{
   file.mkdirs();
   return true;
  }  
 }
 
 public void WriteByByte(String fileName, String str) throws IOException{ //以字节流写文件  
  File file = new File(fileName);
  
  if( !file.exists() )
  {
   System.out.println(fileName + " File doesn't exist");   
   file.createNewFile();
   System.out.println(fileName + " File has created");
  }
  
  FileOutputStream fo = new FileOutputStream(file);
  byte [] content = str.getBytes();
  fo.write(content);
  fo.close();
  
 }
 
 public String ReadByByte(String fileName) throws IOException{ //以字节流读文件
  File file = new File(fileName);
  if ( file.exists() ){   
   FileInputStream fi = new FileInputStream(file);
   byte [] content = new byte[fi.available()];
   fi.read(content);   
   String str = new String(content);
   System.out.println("Read file: " + str.trim());
   fi.close();
   return str.trim();
  }
  else{
   System.out.println("File doesn't exist");
   return "File doesn't exist";
  }
 }
 
 public String ReadByBuffer(String fileName) throws IOException{ //以缓存的方式读文件 
  File file_temp = new File(fileName);
  if ( file_temp.exists() ){
   FileReader file = new FileReader(fileName);
   BufferedReader br = new BufferedReader(file);
   StringBuffer str = new StringBuffer();
   String sw = br.readLine();
   while( sw != null ){
    str.append(sw + "\n");
    sw = br.readLine();
   }
   System.out.println("Read file: " + str);
   return str.toString();
  }
  else{
   System.out.println("File doesn't exist");
   return "File doesn't exist";
  }
 }
  
 public void WriteByBuffer(String fileName, String str) throws IOException{ //以缓存方式写文件
  File file_temp = new File(fileName);
  if ( !file_temp.exists() ){
   System.out.println(fileName + " File doesn't exist");   
   file_temp.createNewFile();
   System.out.println(fileName + " File has created");
  }
  FileWriter file = new FileWriter(fileName);
  BufferedWriter bw = new BufferedWriter(file);
  bw.write(str);
  bw.close();
 }
 
 public boolean DeleteFile(String fileName){ //删除文件
  File file = new File(fileName);
  if( file.exists() ){
   System.out.println("Will delete file: " + fileName);
   if( file.delete() ){
    System.out.println("Have deleted file");
    return true;
   }    
   else{
    System.out.println("Deleted file fail");
    return false;
   }
  }
  else{
   System.out.println("File doesn't exist");
   return false;
  } 
 }
 
 public boolean CopyFileByByte(String fileName1, String fileName2) throws IOException{ //以字节流 复制文件
  File file = new File(fileName1);
  if( !file.exists() ){
   System.out.println(fileName1 + " File doesn't exist");
   return false;
  }
  FileInputStream fi = new FileInputStream(file);
  byte [] content = new byte[fi.available()];
  fi.read(content);
  fi.read(content, 0, content.length);
  String str = new String(content);  
  
  File file_other =new File(fileName2);
  if( !file_other.exists() ){
   System.out.println(fileName2 + "File doesn't exist");
   file_other.createNewFile();
   System.out.println(fileName2 + "File has created");
  }
  FileOutputStream fo = new FileOutputStream (file_other,true);
  fo.write(content);
  fo.flush();
  fo.close();
  fi.close();  
  return true;
 }

 

 public boolean CopyFileByBuffer(String fileName1, String fileName2) throws IOException{ //以缓存方式复制文件
  File file_temp = new File(fileName1);
  if( !file_temp.exists() ){
   System.out.println(fileName1 +  "File doesn't existed");
   return false;
  }
  file_temp = new File(fileName2);
  if( !file_temp.exists() ){
   System.out.println(fileName2 +  "File doesn't existed");
   file_temp.createNewFile();
   System.out.println(fileName2 +  "File has created");
  }
  
  FileReader file = new FileReader(fileName1);
  BufferedReader br = new BufferedReader(file);
  String str = br.readLine();  
  FileWriter file_other = new FileWriter(fileName2);
  BufferedWriter bw = new BufferedWriter(file_other);
  while( str!=null ){
   bw.write(str);
   bw.newLine();
   str = br.readLine();
  }
  bw.flush();
  bw.close();
  br.close();
    
  return false;
 } 
  
}


3. 重定义标准输入输出, 标准输入输出为键盘和屏幕,但是这些都可以自己重定义 为 文件 或其他

                  PrintStream ps = null;		
		try 
		{
			ps = new PrintStream(new FileOutputStream("/home/test/123.txt"));
			System.setOut(ps);  //重定义标准输出到 文件123.txt
			System.out.println("123456789");	
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally 
		{
			ps.close();
		}
                  FileInputStream fis = null;
		try
		{
			fis = new FileInputStream("/home/test/123.txt");			
			System.setIn(fis);  //重定义标准输入为 文件123.txt
			Scanner sc = new Scanner(System.in);
			sc.useDelimiter("\n");		
			while(sc.hasNext())
			{
				System.out.println(sc.next());
			}
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			fis.close();
		}


3. RandomAccessFile 读写文件, 可以操控指针,做到追加和插入文件内容。

public class Main {

	public static void main(String[] args) throws IOException  
	{
		RandomAccessFile raf = null;
		try
		{
			raf = new RandomAccessFile("/home/test/123.txt", "rw");
			System.out.println("point at: " + raf.getFilePointer());
			raf.seek(5);
			System.out.println("point at: " + raf.getFilePointer());
			byte[] buf = new byte[512];
			int hasRead = 0;
			while( (hasRead=raf.read(buf)) > 0 )
			{
				System.out.println(new String(buf, 0, hasRead));
			}
			System.out.println("point at: " + raf.getFilePointer());
			raf.write("add into file\n".getBytes());
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			raf.close();
		}
		
	}
}


4. 保存对象到文件, 对象序列化和反序列化

当使用Java序列化机制序列化可变对象时一定要要注意,只有当第一次调用writeObject方法来输出对象时才会将对象转为字节序列,第二次只会存入一个序列化编号。

class Person implements java.io.Serializable  //序列化的类 需要实现Serializable接口
{
	private String name;
	private int age;
	public Person(String name, int age)
	{
		this.name = name;
		this.age = age;
	}
	int getAge()
	{
		return this.age;
	}
	String getName()
	{
		return this.name;
	}
}

public class Main {

	public static void main(String[] args)
	{
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		try
		{
			oos = new ObjectOutputStream(new FileOutputStream("/home/test/object.txt")); //对象输入流
			Person per = new Person("kevin", 11);
			oos.writeObject(per);   //将对象写入流
			try
			{
				oos.close();
			}
			catch( IOException e )
			{
				e.printStackTrace();
			}
			
			ois = new ObjectInputStream(new FileInputStream("/home/test/object.txt")); //对象反序列
			Person p = (Person)ois.readObject();  //反序列
			System.out.println("Get object from file, name: " + p.getName() + " age: " + p.getAge());
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		finally
		{
			try
			{
				ois.close();
			}
			catch( IOException e )
			{
				e.printStackTrace();
			}
		}
	}
}

 

5. 文件锁

        FileOutputStream fos = new FileOutputStream("file.txt");

        FileChannel fc = fos.getChannel(); //获取FileChannel对象
        FileLock fl = fc.tryLock();  //or fc.lock();
        if(null != fl)
             System.out.println("You have got file lock.");
        //TODO write content to file
        //TODO write end, should release this lock
        fl.release(); //释放文件锁  注意:释放锁要在文件写操作之前,否则会出异常
        fos.close;  //关闭文件写操作


 

posted @ 2013-11-05 09:32  今晚打酱油_  阅读(169)  评论(0编辑  收藏  举报