您的位置:首页 > 编程语言 > Java开发

Java常用工具方法

2017-02-09 16:10 141 查看

以GET请求形式获取文本文件内容

/**
* 以GET请求形式获取文本文件内容
* @param url http下载地址,比如http://www.abc.com/123.css
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String getFileContent(String url) throws ClientProtocolException, IOException{
HttpClient httpCient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpCient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
return response;
}
return null;
}


创建新文件

/**
* 创建新文件
* @param file
* @throws IOException
*/
public static void createNewFile(File file) throws IOException{
/**
* 如果父目录不存在即创建
*/
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.delete();
file.createNewFile();
}


给文本文件追加内容

/**
* 给文本文件追加内容
* @param content
* @param file
* @return
* @throws Exception
*/
public static boolean appendTxtFile(String content, File file) throws Exception {
boolean append = false;
try {
if (file.exists()){
append = true;
}
FileWriter fw = new FileWriter(file, append);
// 创建字符输出流对象
BufferedWriter bf = new BufferedWriter(fw);
// 创建缓冲字符输出流对象
bf.append(content);
bf.flush();
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
return append;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: