打卡—输入/输出基础(一)
1 import java.io.*; 2 import java.awt.*; 3 import java.util.*; 4 public class work_IO { 5 6 public static void main(String[] args) { 7 /* 8 * File类 9 */ 10 File file=new File("word.txt"); //创建文件对象 11 //file.delete(); //删除文件 12 if(file.exists()) { 13 try {//用try捕获可能出现的错误(必须进行) 14 file.createNewFile(); 15 System.out.println("文件创建成功"); 16 //创建FileOutputStream对象 17 FileOutputStream out=new FileOutputStream(file); 18 byte a[]="你好,我进入到文档中去了".getBytes(); // 问题:如何在文档处添加信息,JAVA读取出来 19 //将信息写入到文档 20 out.write(a); 21 //关闭流 22 out.close(); 23 } 24 catch (IOException e) { 25 e.printStackTrace(); 26 } 27 String name=file.getName(); 28 System.out.println("该文件名为:"+name); 29 long length=file.length(); 30 System.out.println("该文件的长度为:"+length); 31 boolean hidden=file.isHidden(); 32 System.out.println("判断该文件是否为隐藏文件:"+hidden); 33 long time=file.lastModified(); //问题:如何设置为时间样式 34 System.out.println("该文件的最后修改时间为:"+time); 35 String pathname=file.getParent(); 36 System.out.println("该文件的父路径为:"+pathname); 37 boolean opinion=file.isFile(); 38 System.out.println("该文件是否存在:"+opinion); 39 String path=file.getAbsolutePath(); 40 System.out.println("该文件的绝对路径为:"+path); 41 boolean write=file.canWrite(); 42 System.out.println("该文件是否可以被写入:"+write); //问题:可以被写入所指的是通过程序写入,还是直接写入 43 try { 44 //创建FileInputStream对象 45 FileInputStream in=new FileInputStream("word.txt"); 46 byte b[]=new byte[1024];//创建byte数组 47 int len=in.read(b);//从文件里读取信息 48 //输出信息 49 System.out.println("文档中的信息为:"+new String(b,0,len)); //问题:为什么是整型转换为字符型 50 in.close(); //问题:流未关闭的坏处 51 /* 52 * 流打开未关闭,造成资源流失,另一个程序尝试打开流时,无法得到需要的资源 53 */ 54 } catch(Exception e){ 55 e.printStackTrace(); //问题:printStackTrace()什么作用 56 } 57 /* 58 * FileWriter类 59 */ 60 try { 61 FileWriter out2=new FileWriter(file); //问题:为什么输入的信息会替换原有的信息 62 Scanner x=new Scanner(System.in); 63 System.out.println("请输入你需要添加进文档的信息:"); 64 String s=x.next(); 65 out2.write(s); 66 out2.close(); 67 }catch(Exception e1){ 68 e1.printStackTrace(); 69 } 70 /* 71 * FileReader类 72 */ 73 try { 74 FileReader in2=new FileReader(file); 75 char byt2[]=new char[1024]; 76 int len2=in2.read(byt2); 77 System.out.println("添加进文档的信息为:"+(new String(byt2,0,len2))); 78 in2.close(); 79 }catch(Exception e2){ 80 e2.printStackTrace(); 81 } 82 83 }else { 84 System.out.println("文件不存在"); 85 } 86 } 87 88 }