java 文件读写实例

网友投稿 233 2022-09-23

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:富士康最底层的挣扎:每天流水线上站10小时 想加班得请领导吃饭!
下一篇:1044 火星数字 (20 分)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~