java 文件读写实例

 

1.dump

将一个文件(图片lion.jpg)复制一份(bbb.bmp)。

主要的部分:使用java.io的InputStream和OutputStream来进行文件输入、输出(write)。

    public static void dump(InputStream src, OutputStream dest)
    throws IOException
    {
        InputStream input = new BufferedInputStream(src);
        OutputStream output = new BufferedOutputStream(dest);
        byte[] data = new byte[1024];
        int length = -1;
        while ((length = input.read(data)) != -1) {
            output.write(data, 0, length);
        }
        input.close();
        output.close();
    }

 

 

 完整代码:

package ch9;
import java.io.*;

public class dump {
	public static void main(String[] args) {
		try
		{
			dump(new FileInputStream("D:\\lion.jpg"),
				 new FileOutputStream("D:\\bbb.bmp"));	
		}
		catch(FileNotFoundException fex)
		{
			fex.printStackTrace();
		}
		catch(IOException ioe)
		{
			ioe.printStackTrace();
		}
	}
	
	public static void dump(InputStream src, OutputStream dest) throws IOException
	{
		InputStream input = new BufferedInputStream(src);
		OutputStream output = new BufferedOutputStream(dest);
		byte[] data = new byte[1024];
		int length = -1;
		while((length = input.read(data))!= -1) {
			output.write(data, 0, length);
		}
		input.close();
		output.close();
	}
	
	
}

 

 

2.ReadLineAndAddNum

读入一个java文件,然后去掉注释,加上行号。

主要部分:

try {
			File fin = new File(infname);
			File fout = new File(outfname);
			
			BufferedReader in = new BufferedReader(new FileReader(fin));
			PrintWriter out = new PrintWriter(new FileWriter(fout));
			
			int cnt =0;
			String s = in.readLine();
			while(s!=null) {
				cnt++;
				s = deleteComments(s);
				out.println(cnt+":\t"+s);
				s = in.readLine();
		}
			in.close();
			out.close();
		}catch(FileNotFoundException e1) {
			System.err.println("File not found");
		}catch(IOException e2) {
			e2.printStackTrace();	
		}
	}

 

package ch9;
import java.io.*;
public class ReadLineAndAddNum {
	public static void main(String[] args) {
		String infname = "C:\\Users\\刘飞\\eclipse-workspace\\ch9\\src\\ch9\\CopyFileAddLineNumber.java";
		String outfname = "C:\\Users\\刘飞\\eclipse-workspace\\ch9\\src\\ch9\\CopyFileAddLineNumber.txt";
		if(args.length >=1) infname = args[0];
		if(args.length>=2) outfname = args[1];
		
		try {
			File fin = new File(infname);
			File fout = new File(outfname);
			
			BufferedReader in = new BufferedReader(new FileReader(fin));
			PrintWriter out = new PrintWriter(new FileWriter(fout));
			
			int cnt =0;
			String s = in.readLine();
			while(s!=null) {
				cnt++;
				s = deleteComments(s);
				out.println(cnt+":\t"+s);
				s = in.readLine();
		}
			in.close();
			out.close();
		}catch(FileNotFoundException e1) {
			System.err.println("File not found");
		}catch(IOException e2) {
			e2.printStackTrace();	
		}
	}
	
	static String deleteComments(String s)
	{
		if(s==null) return s;
		int pos = s.indexOf("//");
		if(pos<0) return s;
		return s.substring(0, pos);
	}
	
}

 

你可能感兴趣的:(JAVA)