`
liujiawinds
  • 浏览: 131923 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

各种IO程序(适合初学者)

    博客分类:
  • java
io 
阅读更多


public class FilenameFilterTest {
	public static void main(String[] args){
		File file=new File(".");
		String[] nameList=file.list(new MyFilenameFilter());
		for(String name: nameList){	
			System.out.println(name);
		}
	}
}
class MyFilenameFilter implements FilenameFilter{

	public boolean accept(File dir, String name) {
		return name.endsWith(".java")||new File(name).isDirectory();//如果文件名以.java结尾,或者是文件夹,返回true
	}
	
}


public class FileInputStreamTest {
	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("src/IO/FileInputStreamTest.java");//创建字符输入流
		byte[] bbuf = new byte[1024];//创建一个长度为1024的数组
		int hasRead = 0;//用于保存实际读取的字节数
		while ((hasRead = fis.read(bbuf))>0) {//循环取水
			System.out.print(new String(bbuf, 0, hasRead));//取出数组中的字节,将字节数组转换为字符串输出
		}
		fis.close();
		
	}
}


public class FileOutputStreamTest {
	public static void main(String[] args) throws IOException{
		FileInputStream fis =new FileInputStream("src/Add.java");//创建字节输入流
		FileOutputStream fos=new FileOutputStream(new File("test.txt"));//创建字节输出流
		byte[] bbuf=new byte[1024];
		int hasRead=0;
		while((hasRead=fis.read(bbuf))>0){
			fos.write(bbuf,0,hasRead);//把输入流的内容写到输出流中
		}
	}
}



public class Test {
	  public static void main(String[] args) {  
		  
	        transForm(System.in,System.out);  
	        //将从键盘输入的小写字母转换成大写的字母      
	    }  
	    public static void transForm(InputStream in,OutputStream out){  
	        int info = 0;  
	        try {  
	            while((info = in.read()) != -1){  
	                //读取信息  
	                int uppInfo = Character.toUpperCase((char)info);  
	                //将 读出的字节信息 转化成大写  
	                out.write(uppInfo);  
	            }  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	          
	    }  
	  
	}  


public class FileWriterTest {
	public static void main(String[] args) throws IOException{
		FileWriter fw=new FileWriter("test.txt");//如果要写其它路径,记得要是“/”
		fw.write("锦瑟--李商隐\r\n");//\r\n换行
		fw.write("锦瑟无端五十弦,一弦一柱思华年\r\n");
		fw.write("庄生晓梦迷蝴蝶,望帝春心托杜鹃\r\n");
		fw.write("沧海月明珠有泪,蓝田日暖玉生烟\r\n");
		fw.write("此情可待成追忆,只是当时已惘然\r\n");
		if(fw!=null){
			fw.close();//记得要关闭字符流,因为它有缓冲功能。强制清空缓冲区也行,flush
		}
	}
}


相对来说,字节流更好使,
因为字节流在操作的时候是直接与文件本身进行关联的,不使用缓冲区
              · 字节文件  字节流直接实现底层的IO操作;
       字符流在操作的时候是通过缓冲区与文件进行操作的,使用缓冲区
              · 字符缓冲文件
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics