书上写的有点乱,所以就自己总结了一下,主要参考: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 ",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()等,如果不知道什么输入,直接按照字符串处理。