java怎么读取数据

angryTom
angryTom 原创
2019-11-12 13:18:49 3680浏览

java怎么读取数据

1、从控制台读取数据

使用Scanner类来读取控制台的输入(推荐教程:java教程

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
  String a = in.nextLine();
  System.out.println(a);
}

2、从本地读取文件

使用FileInputStream、InputStreamReader、BufferedReader类读取本地数据

 public void readTxtFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                    System.out.println(lineTxt);
                }
                br.close();
            } else {
                System.out.println("文件不存在!");
            }
        } catch (Exception e) {
            System.out.println("文件读取错误!");
        }
    }

3、从网络读取文件

使用URLConnection 、InputStreamReader、BufferedReader读取网络数据。

public class Main {
    public static void main(String[] args) {
    String url = "//m.sbmmt.com/test.txt";
    String result = "";
    BufferedReader in = null;
    try {
        //生成URL
        URL realUrl = new URL(url);
        //初始化连接到特定URL的连接通道
        URLConnection connection = realUrl.openConnection();
        //开始实际连接
        connection.connect();
        //数据读取
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        
        //临时存储一行数据
        String line;
        while((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    System.out.println(result);
  }
}

以上就是java怎么读取数据的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。