[英]Creating a java programming to webpage source code with user input file name
我正在嘗試處理將源代碼捕獲到文件中的程序。 我嘗試以其他方式使其正常工作,但似乎無法正常工作。 例如,我想捕獲網頁源代碼,並允許用戶將程序保存為.txt格式。 有人可以幫我嗎? `
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.io.File;
import java.io.FileWriter;
public class ReadFromWeb {
public static void readFromWeb(String webURL) throws IOException {
URL url = new URL(webURL); // create a new url
InputStream is = url.openStream(); //input
//read url
try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
throw new MalformedURLException("URL is malformed!!");
}
catch (IOException e) {
e.printStackTrace();
throw new IOException();
}
}
public static void main(String[] args) throws IOException {
Scanner login = new Scanner(System.in);
Scanner cn= new Scanner(System.in); //create case name scaner
Scanner sc = new Scanner(System.in); // create the scanner for capture webpage
String Username;
String Password;
Username = "steven";
Password = "1234";
System.out.println("enter username : ");
String username = login.next();
System.out.println("enter password : ");
String password= login.next();
if (username.equals(Username)&& (password.equals(Password))){
System.out.println("logged in");
//create file name and save file
System.out.println("enter case number :" );
String input = cn.nextLine().trim();
File file = new File(input);
file.createNewFile();
//write into file
FileWriter writer = new FileWriter(file);
System.out.println("enter URL : ");
String print;
String url = sc.nextLine(); // read the URL
readFromWeb(url); //show the url source data
// writer.write(print); //write into file
// writer.close(); //write close
}
else if (username.equals(Username)){ //invalid password
System.out.println ("invalid password");
}
else if (password.equals(Password)){ //invalid username
System.out.println("Invalid username");
}
else { //invalid bth username and password
System.out.println("invalid username & password");
System.exit(0);
}
}
}
`
因此,基本上該程序要求用戶登錄,然后文件名將與用戶輸入的情況相同。 之后,用戶粘貼網址,系統將捕獲該網址並將其保存到文件中。 但是可行的方法是我無法將文件保存到用戶輸入的文件名中。
您甚至都沒有嘗試向輸出文件中寫入內容。
我看到三種可能的解決方案:
為此,更改readFromWeb
的名稱以download
並聲明第二個參數,該參數采用File
。 然后,讓while循環將line
寫入文件,而不是stdout
。
優點:
缺點:
無需將行寫到stdout
,而是將StringBuilder
附加到一個大的胖String
,然后從您的方法中將其返回(不要忘記手動添加換行符)。
優點:
缺點:
而不是通過while
循環處理方法中的行,而是使用BufferedReader
的lines()
方法獲得的線流。 然后將forEach()
與PrintWrite
的println()
方法一起使用(您需要在其中放置FileWriter
這是必需的,因為append()
不會給您換行符)。
優點:
缺點:
更新 :由於最初的想法需要對BufferedReader
實例進行更復雜的管理,因此我更新了答案,以直接使用方法中的行流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.