java怎么读取数据

java怎么读取数据,第1张

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怎么读取数据的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/687083.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-21
下一篇 2022-04-21

发表评论

登录后才能评论

评论列表(0条)

保存