📄 geturl.java
字号:
// GetURL.java
/*
* Run this with: java GetURL dir URL [ URL ... ]
* This program takes a list of URLs and copies the contents to files
* with the same name as in the URL (minus the path); these files are
* put in the directory 'dir'.
* @author: Ronald Tschaler (Ronald.Tschaler@psi.ch)
*/
import java.net.*;
import java.io.*;
class GetURL
{
static final int buf_size = 4000; // size of buffer used for copying
public static void main (String args[])
{
int idx,
tail,
numb,
dir_idx = 0;
boolean noisy = false;
byte buffer[] = new byte[buf_size];
String outfile;
URL url;
InputStream in;
FileOutputStream out;
/*** get command line options ***/
while (dir_idx < args.length && args[dir_idx].startsWith("-"))
{
if (args[0].equals("-noisy"))
{
noisy = true;
}
else
{
System.err.println("Unknown option: "+args[0]);
return;
}
dir_idx++;
}
/*** check for correct number of command line arguments ***/
if (args.length < dir_idx+2)
{
System.err.println("Usage: java GetURL [-noisy] directory URL "+
"[URL ...]");
System.err.println(" copies the files specified by the "+
"URL's into directory");
return;
}
/*** Get the files ***/
for (idx=dir_idx+1; idx<args.length; idx++)
{
/*** Open URL ***/
try
url = new URL(args[idx]);
catch (MalformedURLException e)
{
System.err.println("Error: malformed URL " + args[idx]);
System.err.println(e.getMessage());
continue;
}
try
in = url.openStream();
catch (IOException e)
{
System.err.println("Error: couldn't access " + args[idx]);
System.err.println(e.getMessage());
continue;
}
/*** extract filename and open file ***/
tail = args[idx].lastIndexOf('\\');
if (tail == -1)
tail = args[idx].lastIndexOf('/');
outfile = args[idx].substring(tail + 1);
try
out = new FileOutputStream(args[dir_idx] + '/' + outfile);
catch (IOException e)
{
System.err.println("Error: couldn't create " + args[dir_idx] +
'/' + outfile);
System.err.println(e.getMessage());
continue;
}
/*** get the file ***/
if (noisy)
System.out.println("Copying "+outfile+"...");
try
{
while ((numb = in.read(buffer)) != -1)
out.write(buffer, 0, numb);
}
catch (IOException e)
{
System.err.println("Error: IOException during copy");
System.err.println(e.getMessage());
continue;
}
/*** cleanup ***/
try in.close(); catch (IOException e) { }
try out.close(); catch (IOException e) { }
}
if (noisy)
System.out.println("Done");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -