java线程读取文件,可以同时读写 202006031002

package org.jimmy.monitor.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

public class FileTest {

    public static String path = "E:/Test/test.txt";
    
    public static void main(String[] args){
        test();
    }
    
    public static void test(){
        ReadThread readThread = new ReadThread();  
        Thread thread1 = new Thread(readThread, "readThread");  
        thread1.start();  
    }
    
    static class WriteThread implements Runnable {  
          
        @Override  
        public void run() {  
            try {  
                File file = new File(path);  
                FileOutputStream fos = new FileOutputStream(file);  
                byte[] b = "hello".getBytes(); 
                boolean flag = true;
                while (flag) {  
                    fos.write(b);  
                    fos.flush();  
                    Thread.sleep(1000);  
                }  
                fos.flush();
                fos.close();
            } catch (Exception e) {  
                e.printStackTrace();  
            }
        }  
  
    }  
    
    static class ReadThread implements Runnable {  
          
        @Override  
        public void run() {  
            try {    
                int cacheLength = 1024;
                boolean flag = true;
                while(flag){
                    FileInputStream fis = new FileInputStream(path);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
                    int fileLength = fis.available();
                    if(fileLength < cacheLength) {
                        cacheLength = fileLength;
                    }
                    int len = cacheLength;
                    char[] chars = new char[cacheLength];
                    while((len = br.read(chars, 0, len)) != -1) {
                        String text = new String(chars);
                        System.out.println(text);
                        Thread.sleep(1000);
//                        sb.append(text);
                    }
                    br.close();
                    fis.close();
                }
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        
    }  
    
}

 

posted @ 2020-06-03 10:02  ラピスラズリ(Dawn)  阅读(400)  评论(0编辑  收藏  举报