「java创建url」Java创建线程

博主:adminadmin 2022-12-14 05:06:09 89

本篇文章给大家谈谈java创建url,以及Java创建线程对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

用java怎么写URL接口

在java中,调用http请求接口,主要通过流的方式进行调用,示例接口如下:

/**

* 程序中访问http数据接口

*/

public String searchLoginService(String urlStr) {

/** 网络的url地址 */

URL url = null;

/** http连接 */

HttpURLConnection httpConn = null;

/**//** 输入流 */

BufferedReader in = null;

StringBuffer sb = new StringBuffer();

try{

url = new URL(urlStr);

in = new BufferedReader( new InputStreamReader(url.openStream(),"UTF-8") );

String str = null;

while((str = in.readLine()) != null) {

sb.append( str );

}

} catch (Exception ex) {

logger.error(ex.getMessage(), ex);

} finally{

try{

if(in!=null) {

in.close();

}

}catch(IOException ex) {

logger.error(ex.getMessage(), ex);

}

}

String result =sb.toString();

System.out.println(result);

return result;

}

java建立url请求 服务器怎么写

//get请求

public String get(String url){

HttpURLConnection conn = null;

BufferedReader rd = null ;

StringBuilder sb = new StringBuilder ();

String line = null ;

String response = null;

try {

conn = (HttpURLConnection) new URL(url).openConnection();

conn.setRequestMethod("GET");

conn.setDoInput(true);

//conn.setReadTimeout(20000);

//conn.setConnectTimeout(20000);

conn.setUseCaches(false);

conn.connect();

rd = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8"));

while ((line = rd.readLine()) != null ) {

sb.append(line);

}

response = sb.toString();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

try {

if(rd != null){

rd.close();

}

if(conn != null){

conn.disconnect();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return response;

}

//post表单请求

public String post(String url, MapString, String form){

HttpURLConnection conn = null;

PrintWriter pw = null ;

BufferedReader rd = null ;

StringBuilder out = new StringBuilder();

StringBuilder sb = new StringBuilder();

String line = null ;

String response = null;

for (String key : form.keySet()) {

if(out.length()!=0){

out.append("");

}

out.append(key).append("=").append(form.get(key));

}

try {

conn = (HttpURLConnection) new URL(url).openConnection();

conn.setRequestMethod("POST");

conn.setDoOutput(true);

conn.setDoInput(true);

//conn.setReadTimeout(20000);

//conn.setConnectTimeout(20000);

conn.setUseCaches(false);

conn.connect();

pw = new PrintWriter(conn.getOutputStream());

pw.print(out.toString());

pw.flush();

rd = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8"));

while ((line = rd.readLine()) != null ) {

sb.append(line);

}

response = sb.toString();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

try {

if(pw != null){

pw.close();

}

if(rd != null){

rd.close();

}

if(conn != null){

conn.disconnect();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return response;

}

java中如何实现URL类?

import java.io.*;

import java.net.*;

public class URLTest

{

public static void main(String[] args)

{

try

{

URL url=new URL("");//创建资源类型

String protocol=url.getProtocol();//获取资源类型

String host=url.getHost();//获取域名

int port=url.getPort();//获取端口

String file=url.getFile();//获取路径

System.out.println("url地址的资源类型为:"+protocol+"域名为:"+host+"端口为:"+port+"路径为:"+file);

InputStream is=url.openStream();//获取页面信息流

BufferedReader bfr=new BufferedReader(new InputStreamReader(is));//封装成字符流

String len;

while((len=bfr.readLine())!=null)

{

System.out.println(len);

}

bfr.close();

is.close();

}

catch(MalformedURLException e)

{

System.out.println("创建URL对象发生异常");

}

catch(IOException e)

{

System.out.println("发生IO操作异常");

}

}

}

如何用java程序实现上传文件到指定的URL地址

参考代码如下:

import java.io.*;

/**

* 复制文件夹或文件夹

*/

public class CopyDirectory {

// 源文件夹

static String url1 = "f:/photos";

// 目标文件夹

static String url2 = "d:/tempPhotos";

public static void main(String args[]) throws IOException {

// 创建目标文件夹

(new File(url2)).mkdirs();

// 获取源文件夹当前下的文件或目录

File[] file = (new File(url1)).listFiles();

for (int i = 0; i file.length; i++) {

if (file[i].isFile()) {

// 复制文件

copyFile(file[i],new File(url2+file[i].getName()));

}

if (file[i].isDirectory()) {

// 复制目录

String sourceDir=url1+File.separator+file[i].getName();

String targetDir=url2+File.separator+file[i].getName();

copyDirectiory(sourceDir, targetDir);

}

}

}

// 复制文件

public static void copyFile(File sourceFile,File targetFile)

throws IOException{

// 新建文件输入流并对它进行缓冲

FileInputStream input = new FileInputStream(sourceFile);

BufferedInputStream inBuff=new BufferedInputStream(input);

// 新建文件输出流并对它进行缓冲

FileOutputStream output = new FileOutputStream(targetFile);

BufferedOutputStream outBuff=new BufferedOutputStream(output);

// 缓冲数组

byte[] b = new byte[1024 * 5];

int len;

while ((len =inBuff.read(b)) != -1) {

outBuff.write(b, 0, len);

}

// 刷新此缓冲的输出流

outBuff.flush();

//关闭流

inBuff.close();

outBuff.close();

output.close();

input.close();

}

// 复制文件夹

public static void copyDirectiory(String sourceDir, String targetDir)

throws IOException {

// 新建目标目录

(new File(targetDir)).mkdirs();

// 获取源文件夹当前下的文件或目录

File[] file = (new File(sourceDir)).listFiles();

for (int i = 0; i file.length; i++) {

if (file[i].isFile()) {

// 源文件

File sourceFile=file[i];

// 目标文件

File targetFile=new

File(new File(targetDir).getAbsolutePath()

+File.separator+file[i].getName());

copyFile(sourceFile,targetFile);

}

if (file[i].isDirectory()) {

// 准备复制的源文件夹

String dir1=sourceDir + "/" + file[i].getName();

// 准备复制的目标文件夹

String dir2=targetDir + "/"+ file[i].getName();

copyDirectiory(dir1, dir2);

}

}

}

}

java构造方法URL(URL urlobj,String urlSpecifier)是什么意思?

有参构造:

意思是你使用这个构造方法创建对象的时候需要给他传递两个参数。一个参数是URL类型(对象本身的类型),另一个字符串类型。列如 URL rul = new URL(new URL(),"str");

源码:

public URL(URL context, String spec) throws MalformedURLException {

this(context, spec, null);

}

两个参数的构造里调用了三个参数的构造。

具体三参数的构造可以参考源码

/**

* Creates a URL by parsing the given spec with the specified handler

* within a specified context. If the handler is null, the parsing

* occurs as with the two argument constructor.

*

* @param context the context in which to parse the specification.

* @param spec the {@code String} to parse as a URL.

* @param handler the stream handler for the URL.

* @exception MalformedURLException if no protocol is specified, or an

* unknown protocol is found, or {@code spec} is {@code null}.

* @exception SecurityException

* if a security manager exists and its

* {@code checkPermission} method doesn't allow

* specifying a stream handler.

* @see java.net.URL#URL(java.lang.String, java.lang.String,

* int, java.lang.String)

* @see java.net.URLStreamHandler

* @see java.net.URLStreamHandler#parseURL(java.net.URL,

* java.lang.String, int, int)

*/

public URL(URL context, String spec, URLStreamHandler handler)

throws MalformedURLException

{

String original = spec;

int i, limit, c;

int start = 0;

String newProtocol = null;

boolean aRef=false;

boolean isRelative = false;

// Check for permission to specify a handler

if (handler != null) {

SecurityManager sm = System.getSecurityManager();

if (sm != null) {

checkSpecifyHandler(sm);

}

}

try {

limit = spec.length();

while ((limit 0) (spec.charAt(limit - 1) = ' ')) {

limit--; //eliminate trailing whitespace

}

while ((start limit) (spec.charAt(start) = ' ')) {

start++; // eliminate leading whitespace

}

if (spec.regionMatches(true, start, "url:", 0, 4)) {

start += 4;

}

if (start spec.length() spec.charAt(start) == '#') {

/* we're assuming this is a ref relative to the context URL.

* This means protocols cannot start w/ '#', but we must parse

* ref URL's like: "hello:there" w/ a ':' in them.

*/

aRef=true;

}

for (i = start ; !aRef (i limit)

((c = spec.charAt(i)) != '/') ; i++) {

if (c == ':') {

String s = spec.substring(start, i).toLowerCase();

if (isValidProtocol(s)) {

newProtocol = s;

start = i + 1;

}

break;

}

}

// Only use our context if the protocols match.

protocol = newProtocol;

if ((context != null) ((newProtocol == null) ||

newProtocol.equalsIgnoreCase(context.protocol))) {

// inherit the protocol handler from the context

// if not specified to the constructor

if (handler == null) {

handler = context.handler;

}

// If the context is a hierarchical URL scheme and the spec

// contains a matching scheme then maintain backwards

// compatibility and treat it as if the spec didn't contain

// the scheme; see 5.2.3 of RFC2396

if (context.path != null context.path.startsWith("/"))

newProtocol = null;

if (newProtocol == null) {

protocol = context.protocol;

authority = context.authority;

userInfo = context.userInfo;

host = context.host;

port = context.port;

file = context.file;

path = context.path;

isRelative = true;

}

}

if (protocol == null) {

throw new MalformedURLException("no protocol: "+original);

}

// Get the protocol handler if not specified or the protocol

// of the context could not be used

if (handler == null

(handler = getURLStreamHandler(protocol)) == null) {

throw new MalformedURLException("unknown protocol: "+protocol);

}

this.handler = handler;

i = spec.indexOf('#', start);

if (i = 0) {

ref = spec.substring(i + 1, limit);

limit = i;

}

/*

* Handle special case inheritance of query and fragment

* implied by RFC2396 section 5.2.2.

*/

if (isRelative start == limit) {

query = context.query;

if (ref == null) {

ref = context.ref;

}

}

handler.parseURL(this, spec, start, limit);

} catch(MalformedURLException e) {

throw e;

} catch(Exception e) {

MalformedURLException exception = new MalformedURLException(e.getMessage());

exception.initCause(e);

throw exception;

}

}

java 怎么使用远程 url 创建 file

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

/**

 * @author lmq

 * 

 */

public class RemoteFile {

public static void main(String[] args) throws Exception {

File remoteFile = new File("//192.168.7.146/test/1.txt");// 192.168.7.146是对方机器IP,test是对方那个共享文件夹名字,如果没有共享是访问不到的

//远程文件其实主要是地址,地址弄对了就和本地文件没什么区别 ,windows里面//或者\\\\开头就表示这个文件是网络路径了其实这个地址就像我们再windows里面,点击开始

//然后点击运行,然后输入 \\192.168.7.146/test/1.txt访问远程文件一样的

BufferedReader br = new BufferedReader(new FileReader(remoteFile));

String str;

while ((str = br.readLine()) != null) {

System.out.println(str);

}

br.close();

}

}

如果是非共享文件 你只能通过url读取流来生成了

public void downUrlTxt(String fileName,String fileUrl,String downPath){

File savePath = new File(downPath);

      if (!savePath.exists()) {   

          savePath.mkdir();   

      }  

      String[] urlname = fileUrl.split("/");  

      int len = urlname.length-1;  

      String uname = urlname[len];//获取文件名  

      try {  

          File file = new File(savePath+"/"+uname);//创建新文件  

          if(file!=null  !file.exists()){  

              file.createNewFile();  

          }  

          OutputStream oputstream = new FileOutputStream(file);  

          URL url = new URL(fileUrl);  

          HttpURLConnection uc = (HttpURLConnection) url.openConnection();  

          uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true  

          uc.connect();  

          InputStream iputstream = uc.getInputStream();  

          System.out.println("file size is:"+uc.getContentLength());//打印文件长度  

          byte[] buffer = new byte[4*1024];  

          int byteRead = -1;     

          while((byteRead=(iputstream.read(buffer)))!= -1){  

              oputstream.write(buffer, 0, byteRead);  

          }  

          oputstream.flush();    

          iputstream.close();  

          oputstream.close();  

      } catch (Exception e) {  

          System.out.println("读取失败!");  

          e.printStackTrace();  

      }        

      System.out.println("生成文件路径:"+downPath+fileName); 

}

关于java创建url和Java创建线程的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-12-14,除非注明,否则均为首码项目网原创文章,转载请注明出处。