file 同时 读写删除
1,同时可以读写,写写,但读写时不能删除。运行下面代码并通过输出验证
package test;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.nio.file.Files;public class TestFile { public static void main( String[] args ) { final TestFile testFile = new TestFile(); new Thread(new Runnable() { @Override public void run() { for(int i = 0; i< 10; i++){ try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { e.printStackTrace(); } testFile.write( Thread.currentThread() + "- line - "+i +"\n"); } } }).start(); new Thread(new Runnable() { @Override public void run() { for(int i = 0; i< 10; i++){ try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { e.printStackTrace(); } testFile.read(); } } }).start(); new Thread(new Runnable() { @Override public void run() { for(int i = 0; i< 10; i++){ try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { e.printStackTrace(); } testFile.write( Thread.currentThread() + "- line - "+i +"\n"); } } }).start(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep( 500 ); Files.delete( new File( "d:/a.txt" ).toPath() ); } catch ( Exception e ) { //java.nio.file.FileSystemException: d:\a.txt: The process cannot access the file because it is being used by another process. e.printStackTrace(); } } }).start(); } private void write(String str){ try { FileOutputStream fos = new FileOutputStream( "d:/a.txt",true ); fos.write( str.getBytes() ); } catch ( Exception e ) { // TODO Auto-generated catch block e.printStackTrace(); } } private void read(){ try { FileInputStream fis = new FileInputStream( "d:/a.txt" ); BufferedReader br = new BufferedReader( new InputStreamReader( fis ) ); String str = br.readLine(); while(str != null){ System.out.println(str); str = br.readLine(); } } catch ( Exception e ) { // TODO Auto-generated catch block e.printStackTrace(); } } }
?2,必须流关闭才能删除,rename(这个很特殊,win与linux下表现不同,getName()也很神奇)。外部流和内部类close效果一样。因为是委托代理组合,内部类的close
import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;public class TestFile { public static void main( String[] args ) { final TestFile testFile = new TestFile(); testFile.write( "test - line -1. \n" ); } private void write( String str ) { try { File file = new File( "d:/a.txt" ); FileOutputStream fos = new FileOutputStream( file, true ); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( fos )); bw.write( str ); System.out.println(file.renameTo( new File( "d:/a1.txt" ) )); System.out.println(file.getName()+" delete result = " + file.delete()); bw.close(); fos.close(); System.out.println(file.renameTo( new File( "d:/a1.txt" ) )); System.out.println(file.getName()+" delete result = " + file.delete()); } catch ( Exception e ) { e.printStackTrace(); } }}
?