java:文本I/O实例

通过文本I/O记录数据,保存了文本信息,即使关机重启,数据也会保存起来...

最主要用到File类(声明文件对象)、PrintWriter类(写数据到文本中)、Scanner类(从文本中读数据)

View Code
 1 //写数据到文件中
 2 import java.io.* ;
 3 public class WriteData
 4 {
 5    public static void main(String[] args) throws Exception
 6    {
 7        File file = new File("score.txt") ;//声明一个文件
 8        if(file.exists())
 9        {
10            System.out.println("File already exist") ;
11            System.exit(0) ;
12         }
13        
14        PrintWriter output = new PrintWriter(file) ;//使用PrintWriter写入数据
15        output.print("John T Smith ") ;
16        output.println(90) ;
17        output.print("Eric K Jones ") ;
18        output.println(85) ;
19        
20        output.close() ;//关闭输入流
21     }
22 }
View Code
 1 //从文件中读数据
 2 import java.io.* ;
 3 import java.util.* ;
 4 public class ReadData
 5 {
 6    public static void main(String[] args) throws Exception
 7    {
 8        File file = new File("score.txt") ;
 9        
10        Scanner input = new Scanner(file) ;//使用Scanner读数据
11        while(input.hasNext())
12        {
13            String firstName = input.next() ;
14            String mi = input.next() ;
15            String lastName = input.next() ;
16            int score = input.nextInt() ;
17            
18            System.out.println(firstName+" "+mi+" "+lastName+" "+score) ;
19         }
20     }
21 }

推荐阅读:

http://fehly.iteye.com/blog/658998

http://www.cnblogs.com/zhxiang/archive/2011/10/14/2212496.html

 

原文地址:https://www.cnblogs.com/KeenLeung/p/2699402.html