例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();
}
}