码迷,mamicode.com
首页 > 编程语言 > 详细

java复习(8)---I/O

时间:2017-03-24 15:54:07      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:port   inpu   font   print   fileinput   trace   bytes   exist   file   

本节复习java常用i/o,输入输出流。

先放上样例代码、方便参考,可以轻松看懂。

package re08;

import java.io.*;
import java.util.Scanner;

public class IOTest {
    public static void main(String[] args) {

        File file = new File("d:/1.txt");   //File创建
        if (file.exists()) {
            file.delete();
        } else {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            FileOutputStream out = new FileOutputStream(file);  //输出到文件
            byte byteout[] = "it‘s a test. ".getBytes();
            out.write(byteout);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            FileInputStream in = new FileInputStream(file);  //读入文件内容
            byte bytein[] = new byte[1024];
            int len = in.read(bytein);
            System.out.println("The message is: " + new String(bytein, 0, len));
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Scanner sc = new Scanner(System.in);   //Scanner练习熟悉
        String line = sc.nextLine();  //读入行
        String line2 = sc.next();  
        int i = sc.nextInt();   //读入int
        double d = sc.nextDouble();  //读入double
        System.out.println(line + line2 + i + d);

    }

}

FileInputStream、FileOutputStream分别为读入文件,输出到文件,参数为File型,即一个文件存储路径(含文件名)

通过方法:read、write可实现读出和写入。

另外常用的从键盘读入字符为Scanner类。

通过方法:nextLine()、nextInt()等读入。

java复习(8)---I/O

标签:port   inpu   font   print   fileinput   trace   bytes   exist   file   

原文地址:http://www.cnblogs.com/weberweber/p/6611613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!