JAVA文件操作

来源:互联网 发布:精度30米dem数据 编辑:程序博客网 时间:2024/05/17 06:43
package hello.java;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;public class ReadFile {//输出中文会乱码public static void ReadFile(String url) {int b = 0;int num = 0;try {FileInputStream is = new FileInputStream(url);while (-1 != (b = is.read())) {System.out.print((char) b);num++;}is.close();System.out.println("\nread end! there are " + num + " bytes");} catch (FileNotFoundException e) {System.out.println("can not find file");e.printStackTrace();} catch (IOException e) {System.out.println("read error!");e.printStackTrace();}}//解决输出中文乱码的问题public static void FileRead(String url) throws Exception{FileReader reader=null;int b;int num=0;reader=new FileReader(url);while (-1 != (b = reader.read())) {System.out.print((char) b);num++;}reader.close();System.out.println("\nread end! there are " + num + " bytes");}public static void CopyFile(String srcUrl, String desUrl) {int b;int num = 0;try {FileInputStream is = new FileInputStream(srcUrl);FileOutputStream os = new FileOutputStream(desUrl);while (-1 != (b = is.read())) {os.write(b);num++;}System.out.println("\ncopy end! there are " + num + " bytes copyed");is.close();os.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) throws Exception {String url = "d:\\input.txt";String desUrl="d:\\output.txt";ReadFile(url);FileRead(url);CopyFile(url,desUrl);}}