當前位置: 首頁>>代碼示例>>Java>>正文


Java URLConnection.getContentLength方法代碼示例

本文整理匯總了Java中java.net.URLConnection.getContentLength方法的典型用法代碼示例。如果您正苦於以下問題:Java URLConnection.getContentLength方法的具體用法?Java URLConnection.getContentLength怎麽用?Java URLConnection.getContentLength使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.net.URLConnection的用法示例。


在下文中一共展示了URLConnection.getContentLength方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getBytes

import java.net.URLConnection; //導入方法依賴的package包/類
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:21,代碼來源:MethodUtil.java

示例2: downloadZip

import java.net.URLConnection; //導入方法依賴的package包/類
private void downloadZip(String link) throws MalformedURLException, IOException
{
	URL url = new URL(link);
	URLConnection conn = url.openConnection();
	InputStream is = conn.getInputStream();
	long max = conn.getContentLength();
	gui.setOutputText("Downloding file...");
	BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File("update.zip")));
	byte[] buffer = new byte[32 * 1024];
	int bytesRead = 0;
	int in = 0;
	while ((bytesRead = is.read(buffer)) != -1) {
		in += bytesRead;
		fOut.write(buffer, 0, bytesRead);
	}
	fOut.flush();
	fOut.close();
	is.close();
	gui.setOutputText("Download Complete!");

}
 
開發者ID:ObsidianSuite,項目名稱:ObsidianSuite,代碼行數:22,代碼來源:Downloader.java

示例3: getBytes

import java.net.URLConnection; //導入方法依賴的package包/類
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();

    // Fixed #4507227: Slow performance to load
    // class and resources. [stanleyh]
    //
    // Use buffered input stream [stanleyh]
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:26,代碼來源:AppletClassLoader.java

示例4: initPumping

import java.net.URLConnection; //導入方法依賴的package包/類
private void initPumping(URLConnection connection) throws IOException {
    final Date lastModif = new Date(connection.getLastModified());
    final URL realUrl = connection.getURL();
    final String accept = connection.getHeaderField("Accept-Ranges");
    final boolean acceptBytes = accept != null ? accept.contains("bytes"): false;
    final long length = connection.getContentLength();
    pumping.init(realUrl, length, lastModif, acceptBytes);
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:9,代碼來源:Pump.java

示例5: saveSEGY

import java.net.URLConnection; //導入方法依賴的package包/類
private void saveSEGY(OutputStream out) throws IOException {
	if(image==null) throw new IOException("no image loaded");

	String mcsPath = PathUtil.getPath("PORTALS/MULTI_CHANNEL_PATH",
			MapApp.BASE_URL+"/data/portals/mcs/");

	URL url = URLFactory.url( mcsPath + line.getCruiseID().trim() + "/segy/" +
			line.getCruiseID().trim() +"-"+ 
			line.getID().trim() + ".segy" );
	URLConnection urlCon = url.openConnection();
	BufferedInputStream in = new BufferedInputStream(urlCon.getInputStream());
	int length = urlCon.getContentLength();

	// Create a JProgressBar + JDialog
	JDialog d = new JDialog((Frame)null, "Saving SEGY");
	JPanel p = new JPanel(new BorderLayout());
	p.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
	d.setLocationRelativeTo(null);
	JProgressBar pb = new JProgressBar(0,length);
	p.add(new JLabel("Saving " + (length / 1000000) + "mb segy file"), BorderLayout.NORTH);
	p.add(pb);
	d.getContentPane().add(p);

	d.pack();
	d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
	d.setVisible(true);

	byte[] b = new byte[16384];
	int read = in.read(b);
	while (read != -1) {
		out.write(b, 0, read);
		pb.setValue(pb.getValue() + read);
		pb.repaint();
		read = in.read(b);
	}

	out.flush();
	in.close();
	d.dispose();
}
 
開發者ID:iedadata,項目名稱:geomapapp,代碼行數:41,代碼來源:XMImage.java

示例6: downloadZip

import java.net.URLConnection; //導入方法依賴的package包/類
/** Downloads a zip from the url, into a temp file under the given temp dir. */
@SuppressForbidden(reason = "We use getInputStream to download plugins")
private Path downloadZip(Terminal terminal, String urlString, Path tmpDir) throws IOException {
    terminal.println(VERBOSE, "Retrieving zip from " + urlString);
    URL url = new URL(urlString);
    Path zip = Files.createTempFile(tmpDir, null, ".zip");
    URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("User-Agent", "elasticsearch-plugin-installer");
    int contentLength = urlConnection.getContentLength();
    try (InputStream in = new TerminalProgressInputStream(urlConnection.getInputStream(), contentLength, terminal)) {
        // must overwrite since creating the temp file above actually created the file
        Files.copy(in, zip, StandardCopyOption.REPLACE_EXISTING);
    }
    return zip;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:16,代碼來源:InstallPluginCommand.java

示例7: doInBackground

import java.net.URLConnection; //導入方法依賴的package包/類
@Override
protected String doInBackground(String... aurl)
{
	int count;
	try
	{
		URL url = new URL(aurl[0]);
		URLConnection conexion = url.openConnection();
		conexion.connect();

		int lenghtOfFile = conexion.getContentLength();
		Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

		InputStream input = new BufferedInputStream(url.openStream());
		OutputStream output = new FileOutputStream("/sdcard" + folder_mire + folder_update + "/mire.apk");

		byte data[] = new byte[1024];

		long total = 0;

		while ((count = input.read(data)) != -1) 
		{
			total += count;
			publishProgress("" + (int)((total*100) / lenghtOfFile));
			output.write(data, 0, count);
		}
		output.flush();
		output.close();
		input.close();
	} 
	catch (Exception e)
	{ }

	return null;
}
 
開發者ID:MSay2,項目名稱:Mire,代碼行數:36,代碼來源:FragmentAbout.java

示例8: download

import java.net.URLConnection; //導入方法依賴的package包/類
public boolean download(PublishingPackage publishingPackage) {

        File file = new File(getFilePath());
        // The URIs have spaces and we need to encode them or we get a 505 error response
        String encodedUri = INDICATORS_URL + getUri().trim().replace(" ", "%20");
        try {
            if (file.exists() && file.length() > 0) {
                log.debug("File {} already exists, not downloading.", getFilePath());
                return true;
            }

            file.getParentFile().mkdirs();
            file.createNewFile();

            try (FileOutputStream fos = new FileOutputStream(file)) {
                URL url = new URL(encodedUri);
                log.debug("Downloading attachment from: " + url);

                URLConnection connection = url.openConnection();
                ReadableByteChannel websiteChannel = Channels.newChannel(connection.getInputStream());
                long bytesExpected = connection.getContentLength();
                FileChannel fileChannel = fos.getChannel();

                long bytesRead = 0;
                while (bytesRead < bytesExpected) {
                    long read = fileChannel.transferFrom(websiteChannel, bytesRead, DOWNLOAD_CHUNK_SIZE);
                    bytesRead += read;
                    log.debug("Downloaded {} Mb / {} Mb", getMb(bytesRead), getMb(bytesExpected));
                }
            }
            return true;
        } catch (Exception e) {
            migrationReport.report(publishingPackage.getUniqueIdentifier(), ATTACHMENT_NOT_AVAILABLE, encodedUri);
            file.delete(); // Attempt to delete the file as it may be partially downloaded
            return false;
        }
    }
 
開發者ID:NHS-digital-website,項目名稱:hippo,代碼行數:38,代碼來源:Attachment.java

示例9: downloadFile

import java.net.URLConnection; //導入方法依賴的package包/類
public static boolean downloadFile(String url, String location) {
    try {

        final URLConnection connection = createURLConnection(url);

        final int  contentLength = connection.getContentLength();
        final File destination   = new File(location);

        if (destination.exists()) {
            final URLConnection savedFileConnection = destination.toURI().toURL().openConnection();
            if (savedFileConnection.getContentLength() == contentLength) {
                return true;
            }
        } else {
            final File parent = destination.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
        }

        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());

        final FileOutputStream fos = new FileOutputStream(destination);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();

    } catch (IOException exception) {
        exception.printStackTrace();
        return false;
    }

    System.out.println(url + "->" + location);
    return new File(location).exists();
}
 
開發者ID:Parabot,項目名稱:Parabot-317-API-Minified-OS-Scape,代碼行數:35,代碼來源:NetUtil.java

示例10: doTestUnknownContentLength

import java.net.URLConnection; //導入方法依賴的package包/類
protected void doTestUnknownContentLength(
  URL url) throws IOException
{
  URLConnection conn = url.openConnection();
  long actualContentLength = conn.getContentLength();

  assertEquals("Invalid explicit content length",
               -1L, actualContentLength);
}
 
開發者ID:apache,項目名稱:myfaces-trinidad,代碼行數:10,代碼來源:ResourceLoaderTestCase.java

示例11: getFileSize

import java.net.URLConnection; //導入方法依賴的package包/類
@Override
public long getFileSize(String path, boolean virtual) throws IOException {
    long fileSize = -1;
    try {
        URLConnection urlConnection = getURLConnection(path, virtual);
        fileSize = urlConnection.getContentLength();
    } catch (IOException e) {
        // Ignore this. It will always fail for non-file based includes
    }
    return fileSize;
}
 
開發者ID:sunmingshuai,項目名稱:apache-tomcat-7.0.73-with-comment,代碼行數:12,代碼來源:SSIServletExternalResolver.java

示例12: checkUnpackLib

import java.net.URLConnection; //導入方法依賴的package包/類
private static void checkUnpackLib(String filename) {
    String path = "/native/" + filename;
    URL resource = NativeLibraryLoader.class.getResource(path);
    if (resource == null) {
        System.err.println("Not available in classpath: " + path);
    } else {
        File file = new File(filename);
        try {
            URLConnection urlConnection = resource.openConnection();
            int length = urlConnection.getContentLength();
            long lastModified = urlConnection.getLastModified();
            if (!file.exists() || file.length() != length || file.lastModified() != lastModified) {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                try {
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
                    try {
                        IoUtils.copyAllBytes(in, out);
                    } finally {
                        IoUtils.safeClose(out);
                    }
                } finally {
                    IoUtils.safeClose(in);
                }
                if (lastModified > 0) {
                    file.setLastModified(lastModified);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
開發者ID:objectbox,項目名稱:objectbox-java,代碼行數:33,代碼來源:NativeLibraryLoader.java

示例13: getFileSize

import java.net.URLConnection; //導入方法依賴的package包/類
@Override
public long getFileSize(String path, boolean virtual) throws IOException {
	long fileSize = -1;
	try {
		URLConnection urlConnection = getURLConnection(path, virtual);
		fileSize = urlConnection.getContentLength();
	} catch (IOException e) {
		// Ignore this. It will always fail for non-file based includes
	}
	return fileSize;
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:12,代碼來源:SSIServletExternalResolver.java

示例14: getInputStreamOfURL

import java.net.URLConnection; //導入方法依賴的package包/類
public InputStream getInputStreamOfURL(URL downloadURL, Proxy proxy) throws IOException{
    
    URLConnection ucn = null;
    
    // loop until no more redirections are 
    for (;;) {
        if (Thread.currentThread().isInterrupted()) {
            return null;
        }
        if(proxy != null) {
            ucn = downloadURL.openConnection(proxy);
        } else {
            ucn = downloadURL.openConnection();
        }
        HttpURLConnection hucn = doConfigureURLConnection(ucn);

        if(Thread.currentThread().isInterrupted())
            return null;
    
        ucn.connect();

        int rc = hucn.getResponseCode();
        boolean isRedirect = 
                rc == HttpURLConnection.HTTP_MOVED_TEMP ||
                rc == HttpURLConnection.HTTP_MOVED_PERM;
        if (!isRedirect) {
            break;
        }

        String addr = hucn.getHeaderField(HTTP_REDIRECT_LOCATION);
        URL newURL = new URL(addr);
        if (!downloadURL.getProtocol().equalsIgnoreCase(newURL.getProtocol())) {
            throw new ResourceRedirectException(newURL);
        }
        downloadURL = newURL;
    }

    ucn.setReadTimeout(10000);
    InputStream is = ucn.getInputStream();
    streamLength = ucn.getContentLength();
    effectiveURL = ucn.getURL();
    return is;
    
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:45,代碼來源:URLResourceRetriever.java

示例15: downloadFully

import java.net.URLConnection; //導入方法依賴的package包/類
public static void downloadFully(URL url, File target) throws IOException {

        // We don't use the settings here explicitly, since HttpRequests picks up the network settings from studio directly.
        ProgressHandle handle = ProgressHandle.createHandle("Downloading " + url);
        try {
            URLConnection connection = url.openConnection();
            if (connection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) connection).setInstanceFollowRedirects(true);
                ((HttpsURLConnection) connection).setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
                ((HttpsURLConnection) connection).setRequestProperty("Accept-Charset", "UTF-8");
                ((HttpsURLConnection) connection).setDoOutput(true);
                ((HttpsURLConnection) connection).setDoInput(true);
            }
            connection.setConnectTimeout(3000);
            connection.connect();
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                throw new FileNotFoundException();
            }
            handle.start(contentLength);
            OutputStream dest = new FileOutputStream(target);
            InputStream in = connection.getInputStream();
            int count;
            int done = 0;
            byte data[] = new byte[BUFFER_SIZE];
            while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
                done += count;
                handle.progress(done);
                dest.write(data, 0, count);
            }
            dest.close();
            in.close();
        } finally {
            handle.finish();
            if (target.length() == 0) {
                try {
                    target.delete();
                } catch (Exception e) {
                }
            }
        }
    }
 
開發者ID:NBANDROIDTEAM,項目名稱:NBANDROID-V2,代碼行數:43,代碼來源:MavenDownloader.java


注:本文中的java.net.URLConnection.getContentLength方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。