Java读取接口中的数据,并保存到txt文件中!

//创建读取接口中数据的方法
	public static String read() {
		URL url = null;
		BufferedReader reader = null;
		HttpURLConnection connection = null;
		InputStreamReader ins = null;

		try {
			// 设置url地址
			url = new URL("https://***.***.com/api/getStudent");
			System.out.println("已完成20%。。。");
			// 获取连接通道
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接响应时间
			connection.setConnectTimeout(2 * 1000);
			// 设置读取响应时间
			connection.setReadTimeout(2 * 1000);

			// 连接
			connection.connect();
			System.out.println("已完成50%。。。");
			// 输入流
			ins = new InputStreamReader(connection.getInputStream(), "UTF-8");
			// 读取
			reader = new BufferedReader(ins);
			// 创建可变字符串
			StringBuffer sb = new StringBuffer();
			System.out.println("已完成80%。。。");
			String line;

//			readLine()方法,当读取流读取数据时使用,当读到\n、\r时,会跟着换行,
//			同时会以字符串的形式返回这一行,当读取完所有数据时,会返回null
			while ((line = reader.readLine()) != null) {
				System.out.println("导入中。。。");
				sb.append(line + "\n");
			}
			return sb.toString();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Error GetURL:" + e);
			System.out.println("Error GetURL:" + url);
			e.printStackTrace();
		} finally {
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;

	}
//写文件处理
	public static void main(String[] args) {
		System.out.println("导入开始!");
		File file = new File("F:/love.txt");
		
		if(file.exists()) {
			System.err.println("F盘下已存在love.txt的文件,将更新文件内容");
			file.delete();
		}
		
		if(!file.exists()) {
			try {
				file.createNewFile();
				OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file),"GB2312");
				BufferedWriter bw = new BufferedWriter(osw); 
				bw.write(read());
				System.out.println("已完成100%");
				System.out.println("导入结束!");
				bw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


转载于:https://www.cnblogs.com/wjup/p/10576109.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值