第7章java作业

例7-1      如何使用list()方法来检查一个目录的内容

<span style="font-size:18px;color:#6600cc;">import java.io.File;
public class List1 {
public static void main(String args[])
{
	String dirname="\\java";
	File f= new File(dirname);
	if(f.isDirectory())
	{
		System.out.println("Directory of"+dirname);
		String s[]=f.list();
		for(int i=0;i<s.length;i++)
		{
			File f1=new File(dirname +"\\"+s[i]);
			if(f1.isDirectory())
			{
				System.out.println(s[i]+"is a directory");
			}
			else
			{
				System.out.println(s[i]+"is a file");
			}
		}
	}
	else
	{
		System.out.println(dirname+"is not a directory");
			
			}
		}
		
	}
</span>

例7-2     创建一个FileInputStream类对象读取文件中的内容,使用循环判断是否到达文件尾,未到达则按字节输出

import java.io.*;
public class ShowFile {
public static void main(String args[])throws IOException
{ 
	int a;
	FileInputStream f;
	try{
		f=new FileInputStream(args[0]);
	}catch(FileNotFoundException e)
	{
		System.out.println("File not found");
		return;
	}catch(ArrayIndexOutOfBoundsException e)
	{
		System.out.println("Usage:ShowFile File");
		return;
	}
	System.out.print("文件内容是:");
	do{
		a=f.read();
		if(a!=-1)
			System.out.print((char)a);
	}while (a!=-1);
	f.close();
}
}

例7-3     创建一个在指定文件名中写入数据的输出文件流

import java.io.*;
public class FileOut1 {
public static void main(String args[]) throws IOException
{
	String s ="welcome to you!";
	byte b[]=s.getBytes();
	FileOutputStream fo =new FileOutputStream("f.txt");
	fo.write(b);
	fo.close();
}
}

例7-4   实现从输出中读一个字节

import java.io.*;
public class SysR {
public static void main(String args[])throws IOException
{
	char a;
	System.out.print("输入一个字符:");
	a=(char)System.in.read();
	System.out.println("输入的字符是:"+a);
}
}

例7-5   输入多位的整数,使用BufferedReader类的readLine()方法按整数类型输出结果

import java.io.*;
public class Bread {
public static void main(String args[])throws IOException
{
	try
	{
		InputStreamReader r;
		BufferedReader n;
		r=new InputStreamReader(System.in);
		n=new BufferedReader(r);
		String s=n.readLine();
		System.out.println("Input value is:"+s);
		int i=Integer.parseInt(s);
		i*=2;
		System.out.println("Input value changed after doubled:"+i);
	}catch(IOException e)
	{
		System.out.println(e);
	}
}
}

例7-6  从键盘输入一系列字符串,写入到某磁盘文件中

import java.io.*;
public class Bwriter {
public static void main(String args[])throws Exception
{
	InputStreamReader i=new InputStreamReader(System.in);
	BufferedReader b=new BufferedReader(i);
	FileWriter f=new FileWriter("file1.txt");
	BufferedWriter w=new BufferedWriter(f);
	String s;
	while(true)
	{
		System.out.print("input a string:");
	    System.out.flush();
	    s=b.readLine();
	    if(s.length()==0)
	    	break;  //如果用户直接回车,代表结束
	    w.write(s);
	    w.newLine();  
	}
	w.close();
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值