课程6 1905

(1)

import java.io.*;

public class FileInputStreamTest {

    public static void main(String[] args) throws IOException {
        //创建字节输入流
        FileInputStream fis = new FileInputStream("D:\\1.txt");
        //创建一个长度为1024的“竹筒”
        byte[] bbuf = new byte[1024];
        //用于保存实际读取的字节数
        int hasRead = 0;
        //使用循环来重复“取水”过程
        while ((hasRead = fis.read(bbuf)) > 0) {
            //取出“竹筒”中水滴(字节),将字节数组转换成字符串输入!
            System.out.print(new String(bbuf, 0, hasRead));
        }
        fis.close();
    }
}

(2)

import java.io.*;

public class FileReaderTest
{
 public static void main(String[] args) throws IOException
 {
  FileReader fr = null;
  try
  {
   //创建字符输入流
   fr = new FileReader("D:\\1.txt");
   //创建一个长度为32的“竹筒”
   char[] cbuf = new char[32];
   //用于保存实际读取的字符数
   int hasRead = 0;
   //使用循环来重复“取水”过程
   while ((hasRead = fr.read(cbuf)) > 0 )
   {
    //取出“竹筒”中水滴(字节),将字符数组转换成字符串输入!
    System.out.print(new String(cbuf , 0 , hasRead));
   }
  }
  catch (IOException ioe)
  {
   ioe.printStackTrace();
  }
  finally
  {
   //使用finally块来关闭文件输入流
   if (fr != null)
   {
    fr.close();
   }
  }
 }
}

(3)使用输入流比较两个文件内容

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class InputStreamTest {
    public boolean compareFiles(Path path1, Path path2) 
            throws NoSuchFileException {
        
        if (Files.notExists(path1)) {
            throw new NoSuchFileException(path1.toString());
        }
        if (Files.notExists(path2)) {
            throw new NoSuchFileException(path2.toString());
        }
        try {
            if (Files.size(path1) != Files.size(path2)) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (InputStream inputStream1 = Files.newInputStream(
                    path1, StandardOpenOption.READ);
            InputStream inputStream2 = Files.newInputStream(
                    path2, StandardOpenOption.READ)) {
            
            int i1, i2;
            do {
                i1 = inputStream1.read();
                i2 = inputStream2.read();
                if (i1 != i2) {
                    return false;
                }
            } while (i1 != -1);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        Path path1 = Paths.get("D:\\1.txt");
        Path path2 = Paths.get("D:\\2.txt");
        InputStreamTest test = new InputStreamTest();
        try {
            if (test.compareFiles(path1, path2)) {
                System.out.println("Files are identical");
            } else {
                System.out.println("Files are not identical");
            }
        } catch (NoSuchFileException e) {
            e.printStackTrace();
        }
        
        // the compareFiles method is not the same as Files.isSameFile
        try {
            System.out.println(Files.isSameFile(path1, path2));
        } catch (IOException e) {
            e.printStackTrace();
        }
       

    }
}

(4)使用输出流复制文件

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class OutputStreamTest {
    public void copyFiles(Path originPath, Path destinationPath)
            throws IOException {
        if (Files.notExists(originPath) 
                || Files.exists(destinationPath)) {
            throw new IOException(
                    "Origin file must exist and " + 
                    "Destination file must not exist");
        }
        byte[] readData = new byte[1024];
        try (InputStream inputStream = Files.newInputStream(originPath, 
                StandardOpenOption.READ);
            OutputStream outputStream = Files.newOutputStream(destinationPath, 
                    StandardOpenOption.CREATE)) {
            int i = inputStream.read(readData);
            while (i != -1) {
                outputStream.write(readData, 0, i);
                i = inputStream.read(readData);
            }
        } catch (IOException e) {
            throw e;
        }
    }

    public static void main(String[] args) {
        OutputStreamTest test = new OutputStreamTest();
        Path origin = Paths.get("D:\\1.txt");
        Path destination = Paths.get("D:\\0.txt");
        try {
            test.copyFiles(origin, destination);
            System.out.println("Copied Successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(5)


import java.io.*;

public class PrintStreamTest {

    public static void main(String[] args) throws IOException {
        PrintStream ps = null;
        try {
            //创建一个节点输出流:FileOutputStream
            FileOutputStream fos = new FileOutputStream("D:\\1.txt");
            //以PrintStream来包装FileOutputStream输出流
            ps = new PrintStream(fos);
            //使用PrintStream执行输出
            ps.println("普通字符串");
            ps.println(new PrintStreamTest());
        } catch (IOException ioe) {
            ioe.printStackTrace(ps);
        } finally {
            ps.close();
        }
    }
}

(6)

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.Map;


public class FileWatcherDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //创建一个WatchService对象,此对象将用于管理特定文件夹的变动信息队列。
  try(WatchService service=FileSystems.getDefault().newWatchService()) {
   //此集合可保存多个文件夹的监控信息,当前只使用了一个
   Map<WatchKey, Path> keyMap=new HashMap<>();
   Path path=Paths.get("D:\\1.test");
   //设置WatchService对象管理的内部队列,将保存指定的文件夹的创建、删除和修改事件信息
   //返回的WatchKey对象可用于从事件队列中获取事件对象
   WatchKey key=path.register(service, StandardWatchEventKinds.ENTRY_CREATE,
     StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
   keyMap.put(key, path);
   
   do {
    //开始监控,阻塞等待,当感兴趣的事件发生时,take()方法返回。
    key=service.take();
    Path eventDir=keyMap.get(key);
    //从事件队列中提取所有的事件
    for (WatchEvent<?> event : key.pollEvents()) {
     //是什么类型的事件?
     WatchEvent.Kind<?> kind=event.kind();
     //是哪个对象发生了变动?
     Path eventPath=(Path)event.context();
     System.out.println(eventDir+":"+kind+":"+eventPath);
    }
   } while (key.reset()); //reset方法重置此对象,让其可以重新接收信息
   
  } catch (Exception e) {
   
  }

 }

}

(7)读取文件

import java.io.*;
import java.util.Arrays;

public class duqu {
 public static void main(String[] args) throws IOException {
  File f=new File("D:\\piao.txt");
  FileReader fr=new FileReader(f);
  BufferedReader bufr=new BufferedReader(fr);
  StringBuffer str=new StringBuffer();
  String Line=null;
        while((Line=bufr.readLine())!=null) {
            str.append(Line);
        }
  bufr.close();
  double cishux[]=new double[26];
  double cishud[]=new double[26];
  int count=0;
  for(int i=0;i<str.length();i++) 
  {
   char ch=str.charAt(i);
   if((ch>='A'&&ch<='Z')) 
   {
    for(int j=0;j<26;j++)
    {
     if((ch=='A'+j))
     {
      cishud[j]++;
      break;
     }
     
    }
    count++;
   }
   if((ch>='a'&&ch<='z')) 
   {
    for(int j=0;j<26;j++)
    {
     if((ch=='a'+j))
     {
      cishux[j]++;
      break;
     }
     
    }
    count++;
   }
  }
  double gailvd[]=new double[26];
  double gailvx[]=new double[26];
  System.out.println("一共有"+count+"个字母");
  for(int i=0;i<26;i++) 
   gailvd[i]=cishud[i]/count;
  for(int i=0;i<26;i++) 
   gailvx[i]=cishux[i]/count;
  double gailv[]=new double[52];
  double s[]=new double[52];
  for(int i=0;i<26;i++)
   {gailv[i]=gailvd[i];
   s[i]=gailvd[i];}
  for(int i=26;i<52;i++)
   {gailv[i]=gailvx[i-26];
    s[i]=gailvx[i-26];}
  Arrays.sort(gailv);
  for(int i=51;i>=0;i--) {
            int max=0;
            for(int j=0;j<52;j++) {
                if(gailv[i]==s[j])
                    max=j;
            }
            if(max>=26)
                System.out.print(((char)('a'+max-26))+":");
            else
            System.out.print(((char)('A'+max))+":");
            System.out.println(String.format("%.2f",gailv[i]*100)+'%');
        }

  
  //System.out.print(((char)('A'+i))+":");
  //
}
}

 
 
原文地址:https://www.cnblogs.com/leiyu1905/p/14170158.html