Thursday, March 24, 2005

HowTo Java1--Reading a file directly from net...

import java.net.*;
import java.io.*;
import java.util.*;

public class nettest_version4
{
public static void main(String[] args)throws Exception
{
String myurl_strng;
String mysavedfile_strng;
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
if (args.length == 0)
{

myurl_strng = getUrlFromUser("Enter the url you would like to parse: ");
System.out.println("###################################################");
System.out.println("u r going to parse "+myurl_strng);
System.out.println("###################################################");
System.out.println("######### please wait checking connection #######");
if (myurl_strng.length() == 0) { return; }
}
else
{
myurl_strng = args[0];
}

//URL ckmds_answer=new URL("http://www.yahoo.com");
URL ckmds_answer=new URL(myurl_strng);
URLConnection ckmds_answer_connection=ckmds_answer.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(ckmds_answer_connection.getInputStream()));
String inputLine;
if (args.length == 0)
{
System.out.println("###################################################");
mysavedfile_strng=getFileNameFromUser("Enter the filename you would like to save: ");
System.out.println("u r going to save "+mysavedfile_strng);
if (mysavedfile_strng.length() == 0) { return; }
}
else
{
mysavedfile_strng = args[0];
}

out = new FileOutputStream(mysavedfile_strng);
// Connect print stream to the output stream
p = new PrintStream( out );
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
p.println(inputLine);
}
p.close();
in.close();
}
catch(Exception ex)
{
System.out.println(ex);
System.out.println("######### A proxy server may be in use #######");
System.out.println("###### Please check it and while compiling #####");
System.out.println("# use java -Dhttp.proxyHost= System.out.println("usage:http://www.yahoo.com");
}
}
// private function that gets console input URL from the user
private static String getUrlFromUser(String prompt) throws IOException
{

System.out.print(prompt);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
// private function that gets console input for saving file from the user
private static String getFileNameFromUser(String prompt) throws IOException
{

System.out.print(prompt);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}

}

0 Comments:

Post a Comment

<< Home