首页 > Java > Java基础 > 正文

java怎么读取数据

angryTom
发布: 2019-11-12 13:18:49
原创
4260 人浏览过

java怎么读取数据

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 = "http://www.php.cn/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中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!