Java I/O操作学习笔记
书上写的有点乱,所以就自己总结了一下,主要参考:http://www.cnblogs.com/qianbi/p/3378466.html
1.从文件读出和写入:
1 import java.io.*; 2 import java.util.*; 3 public class FileDemo{ 4 private Formatter f2; 5 public void Fileexists(){ 6 File f1 = new File("D:\\test2.txt"); 7 8 //查看文件test2.txt是否存在 9 if(f1.exists()) 10 System.out.println(f1.getName() + " exists"); 11 else 12 System.out.println("this thing does not exists"); 13 14 } 15 16 17 public void WriteFile(){ 18 BufferedWriter out = null; 19 try{ 20 out = new BufferedWriter(new FileWriter("fred.txt")); 21 out.write("20 sunshineatnoon"); 22 out.newLine(); 23 out.write("21 moment"); 24 }catch(Exception e){ 25 e.printStackTrace(); 26 }finally{ 27 try{ 28 out.close(); 29 }catch(Exception e){ 30 31 } 32 } 33 } 34 35 public void closeFile(){ 36 f2.close(); 37 } 38 39 //按行读取文件 40 public void ReadFile(){ 41 FileReader reader = null; 42 BufferedReader br = null; 43 try{ 44 reader = new FileReader("fred.txt"); 45 br = new BufferedReader(reader); 46 String s1 = null; 47 48 while((s1 = br.readLine()) != null){ 49 System.out.printf("%s\n",s1); 50 } 51 52 }catch(Exception e){ 53 e.printStackTrace(); 54 }finally{ 55 try{ 56 reader.close(); 57 }catch(Exception e){ 58 59 } 60 } 61 } 62 }
2.从控制台输入
public void ReadFromConsle(){ Scanner sc = new Scanner(System.in); System.out.println("输入数字:"); System.out.println("输入的数字为:"+sc.nextInt()); System.out.println("输入字符串:"); System.out.println("输入的字符串为:"+sc.next()); }
类似的还有sc.nextDouble()等,如果不知道什么输入,直接按照字符串处理。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了