java文件流小练习2

在上次的练习之后,我们继续练习文件流

11.

import java.io.*;

public class wenjianlianxi10 {

	/**
	 * @param args缓冲流
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String[] content={"半城烟沙","宿敌","雨幕","放肆","曼陀山庄"};
		File file=new File("F://game/lianxi10.txt");
		try{
			FileWriter f1=new FileWriter(file);
			BufferedWriter b=new BufferedWriter(f1);
			for(String s:content){
				b.write(s);
				b.newLine();
			}
			b.close();
			f1.close();
			
			FileReader f2=new FileReader(file);
			BufferedReader b1=new BufferedReader(f2);
			String s=null;
			while((s=b1.readLine())!=null){
				System.out.println(s);
			}
			b1.close();
			f2.close();
			
		}catch(IOException e){
			System.out.println(e);
		}
	}

}

12.

import java.io.*;

public class wenjianlianxi11 {

	/**
	 * @param args
	 * 数据流,输入数据“纸上雪”,369,true到lianxi11
	 */
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try{
		DataOutputStream data=new DataOutputStream(new FileOutputStream("F://game/lianxi11.txt"));
		data.writeUTF("纸上雪");
		data.writeInt(999);
		data.writeBoolean(true);
		data.close();
		
		DataInputStream da=new DataInputStream(new FileInputStream("F://game/lianxi11.txt"));
		String reads=da.readUTF();
		int ra=da.readInt();
		boolean flang=da.readBoolean();
		da.close();
		
		System.out.println(reads+ra+flang);
		
	    }
		catch(IOException e){
			System.out.println(e);
			}
		}


}

13.

import java.io.*;
public class wenjianlianxi12 {

	/**
	 * @param args对象流序列化
	 * @throws ClassNotFoundException 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try{
			ObjectOutputStream obj=new ObjectOutputStream(new FileOutputStream("F://game/lianxi12.txt"));
			obj.writeUTF("真心");
			obj.writeInt(555);
			obj.writeObject(new ob("千泷",22));
			obj.close();
			
			ObjectInputStream obs=new ObjectInputStream(new FileInputStream(new File("F://game/lianxi12.txt")));
			String s=obs.readUTF();
			int b=obs.readInt();
			Object obb=obs.readObject();
			obj.close();
			System.out.println(s+"  "+b+"  "+obb.toString());
			 
		}
		catch(IOException e){System.out.println(e);}
		catch(ClassNotFoundException e1){System.out.println(e1);}
	}

}

class ob implements Serializable{
	//public static final long serialVersionUID=42123L;
	String name;
	int age;
	public ob(String name,int age){
		this.age=age;
		this.name=name;
		
	}
	
	public String toString(){
		return "真心之人:"+name+"  "+"芳龄:"+age;
	}

}

14.

import java.io.*;
public class wenjian1 {

	/**
	 * @param args
	 * 打开一个文本文件test1.txt,统计该文件中包含的数字的个数与英文字母的个数(忽略大小写)。
	 * 例如test.txt文本文件中包含的内容为"123abcDEF99G”,则程序的输出结果如下:
数字数是5,字母数是7

	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		   byte buf[] = new byte[5];
		      int len= 0 ,c1 = 0,c2=0;
		      //*********Found**********
		      try{
		         //*********Found**********
		         FileInputStream in = new FileInputStream("F://game/test1.txt");
		         while((len =in.read(buf,0,5))>0){
		            for(int i = 0; i < len;i++)
		               if(buf[i]>= '0' && buf[i] <= '9'){
		                  c1 ++;
		               }
		               else 
		                  if((buf[i]>= 'a' && buf[i] <= 'z') || buf[i]>= 'A' && buf[i] <= 'Z') 
		                     c2++;
		            if(len <5) break;
		         }
		         //*********Found**********
		         in.close(); 
		      }catch(Exception e ){}
		      System.out.println("数字数是 " + c1 + ",字母数是 " + c2);
		   }
	}

15.

import java.io.*;

public class wenjian2 {

	/**
	 * @param args
	 * 本题的要求是:
该程序的功能是:将一个对象写入一个数据文件,再读出该对象并显示出来。该程序的运行结果是:小王
F://game/Person.txt

	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 ObjectOutputStream oos = null;
	        ObjectInputStream ois = null;
	        try { 
	            File f = new File("F://game/Person.txt");
	            //*********Found**********
	            oos = new ObjectOutputStream(new FileOutputStream(f));
	            oos.writeObject(new Person("小王"));
	            oos.close();
	            ois = new ObjectInputStream(new FileInputStream(f));
	            //*********Found**********
	            Person d = (Person)ois.readObject();
	            System.out.println(d);
	            ois.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	}

}

class Person implements Serializable {
    String name = null;
    public Person(String s) {
        name = s;
    }
    //*********Found**********
    public String toString() {
        return name;
    }
}

16.

import java.io.*;
public class wenjian3 {

	/**
	 * @param args
	 * 
将四句歌词分行写入到F://game/wenjian3.txt文件中,然后从该文件读出所有内容并显示。
运行结果为;
第1行内容:在那山的那边海的那边有一群蓝精灵
第2行内容:它们活泼又聪明它们调皮又灵敏第
3行内容:它们自由自在生活在那绿色的大森林
第4行内容:它们善良勇敢相互都欢喜!

	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 String ShowMes[] = {"在那山的那边海的那边有一群蓝精灵", "它们活泼又聪明它们调皮又灵敏", "它们自由自在生活在那绿色的大森林", "它们善良勇敢相互都欢喜!"};
	        try {
	            //*********Found********
	            FileWriter out = new FileWriter(new File("F://game/wenjian3.txt"));
	            BufferedWriter outBW = new BufferedWriter(out);
	            for (int i = 0; i < ShowMes.length; i++) {
	                outBW.write(ShowMes[i]);
	                outBW.newLine();
	            }
	            //*********Found********
	            outBW.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        try {
	            //*********Found********
	            FileReader in = new FileReader(new File("F://game/wenjian3.txt"));
	            BufferedReader inBR = new BufferedReader(in);
	            String stext = null;
	            int j = 1;
	            while ((stext = inBR.readLine()) != null) {
	                System.out.println("第" + j + "行内容:" + stext);
	                //*********Found********
	                j++;
	            }
	            inBR.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	}

}

17.

import java.io.*;

public class wenjian4 {

	/**
	 * @param args
	 * 程序的功能是:以两个文件名做为命令行参数,如果两个文件都存在,则将第二个文件的内容追加到第一个文件中,
	 * 并将第二个文件从系统中删除。
程序运行时,将“a.txtb.txt”作为命令行参数,会显示:
has done !
sUCCESS!

	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 if(args.length<2)
	      {
	         System.out.println("ERROR: need parameters.");    
	         System.out.println("\n -usage: java <classname> <file1> <file2>");    
	         System.exit(0);
	      }
	      File f1=new File("F://game/a.txt");
	      //*********Found**********
	      File f2=new File("F://game/b.txt");
	      try
	      {
	         //*********Found**********
	         FileReader fr=new FileReader(f2);
	         FileWriter fw=new FileWriter(f1,true);
	         int b;
	         //*********Found**********
	         while(( b=fr.read() ) != -1 )  fw.write(b);
	         fr.close();
	         fw.close();
	      }
	      catch(IOException e)
	      {
	         e.printStackTrace();
	      }
	      System.out.println("has done!");
	      //*********Found**********
	      if(f2.delete()) System.out.print("SUCCESS!");
		
	}

}

18.

import java.io.*;
import java.util.Vector;

/**
 * @param args
本题的要求是:
1.以行的方式读入每个用户名及其密码信息,例如: user1 123456(用户名和密码之间用一个空格隔开);
2.循环读入,直到用户输入“quit”或者“QUIT”结束;
3.程序结束前提示用户输入一个文件名来保存前面输入的所有用户名和密码信息。例如:请输入存储到的文件名:userlist.txt;
4.在整个上述过程中,要做例外处理;如果文件创建成功,则给出提示信息。


 */

public class wenjian5 {
	public  static void  main(String arg[]){
		 Vector v=new Vector();
	      try{
	         //*********Found**********
	         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));    //键盘输入
	         String str = "";
	         System.out.println("请输入用户和密码信息,中间用空格隔开,输入quit退出:");
	         while (!(str.equals("quit")||str.equals("QUIT"))){
	            str = in.readLine();
	            //*********Found**********
	            if(isValid(str))      //验证输入是否有空格
	               v.add(str);
	            else{
	               if(!(str.equals("quit")||str.equals("QUIT")))
	                  System.out.println("The string is NOT valid!");
	            }
	         }
		        
	         System.out.println("请输入保存到的文件名:");
	         //*********Found**********
	         str=in.readLine();

	         String curDir = System.getProperty("user.dir");
	         File savedfile=new File(curDir+"\\"+str);
	            
	         //*********Found**********
	         BufferedWriter out = new BufferedWriter(new FileWriter(savedfile));
	         for(int i=0; i<v.size(); i++){
	            String tmp=(String)v.elementAt(i);
	            out.write(tmp);
	            //*********Found**********
	            out.write("\n");      //换行
	         }
	         out.close();
	        
	      }
	      //*********Found**********
	      catch(Exception e){
	         System.out.print("ERROR:"+e.getMessage());	
	      }
	   }
	   /**
	   * 判定输入的字符串是否符合规范
	   * @param  s  输入的待校验的字符串
	   * @return    校验的结果,正确则返回为真
	   */
	   public static boolean isValid(String s){
	      if(s.indexOf(" ")>0) return true;
	      else return false;
	   }
	}

19.

import java.io.File;
public class wenjianhuoquliebiao {

	/**
	 * @param args
	 * 获取当前文件夹路径
	 * 程序列出当前目录下所有文件和文件夹的名称。如果当前目录含有子文件夹,
	 * 则也递归地列出子文件夹的内容,用缩进地方式反映层次关系,文件夹的名称用尖括号括起来。某次运行结果如下:
当前的工作目录是:Z: \test
Java_2.class
<source>
<Java1>
Java_1.java
<Java2>
Java_2.java
<Java3>
Java_3.java

	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 //Getting the Current Working Directory
	      String curDir = System.getProperty("user.dir");
	      System.out.println("当前的工作目录是:"+curDir);
			
	      //*********Found**********
	      File ff=new File(curDir);
	      String[] files=ff.list();
	      for(int i=0; i<files.length; i++)
	      {
	         String ss=curDir+"\\"+files[i];
	         traverse(0,ss);	
	      }
		
	}
	 /**
	   * 递归地遍历目录树
	   * @param  level 目录的层次
	   * @param  s     当前目录路径名
	   */
	   public static void traverse(int level,String s)
	   {
	      File f=new File(s);
	      for(int i=0; i<level; i++) System.out.print("   ");
	      if(f.isFile()) 
	      {
	         System.out.println(f.getName());
	      }
	      else if(f.isDirectory())
	      {
	         //*********Found**********
	         System.out.println("<"+f.getName()+">");
	         String[] files=f.list();
	         level++;
	         //*********Found**********
	         for(int i=0; i<files.length;i++)
	         {
	            String ss=s+"\\"+files[i];
	            //*********Found**********
	            traverse(level,ss);
	         }
	      }
	      else
	      {
	         System.out.println("ERROR!");
	      }
	   }

}

20.

import java.io.FileInputStream;

public class lainxi6 {

	/**
	 * @param args
	 * 6.应用FileInputStream类,编写应用程序,从磁盘上读取一个Java程序,
	 * 并将源程序代码显示在屏幕上。(被读取的文件路径为:F:/game/Hello.txt )
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		byte[] buf=new byte[2056];
		try{
			FileInputStream fileIn=new FileInputStream("E:/han/hello.txt");
			int bytes=fileIn.read(buf,0,2056);
			String str=new String(buf,0,bytes);
			System.out.println(str);
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
	
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值