>我正在尝试处理将源代码捕获到文件中的程序。我尝试了另一种方式使其工作,但它似乎不起作用。例如,我想捕获网页源代码并允许用户将程序保存为.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);
}
}
}
'
所以基本上程序要求用户登录,然后文件名将与用户输入的情况相同。 之后,用户粘贴URL,系统将捕获它并将其保存到文件中。 但是可以工作的是我无法将文件保存到用户输入的文件名中。
您甚至没有尝试将某些内容写入输出文件。
我看到三种可能的解决方案:
1. 让你的方法写入输出
为此,请将readFromWeb
的名称更改为download
并声明第二个参数,该参数需要您的File
。然后让 while 循环将line
写入文件,而不是写入stdout
。
优点:
- 内存占用量小(一行的最大大小)
缺点:
- 没有很好的关注点分离,因为您的方法可以同时进行
阿拉伯数字。让您的方法返回内容并将其写入文件
与其将行写入stdout
,不如将它们与StringBuilder
附加到一个大胖String
,然后从您的方法中返回(不要忘记手动添加换行符)。
优点:
- 关注点分离(从网络读取/输出到文件)
缺点:
- 一个大缓冲区(对于大文件不是很好)
3.返回使用线路流
不要通过while
循环处理方法中的行,而是使用BufferedReader
slines()
方法获取的行流。然后将forEach()
与PrintWrite
的println()
方法一起使用(您需要将FileWriter
放在那里 - 这是必要的,因为append()
不会给您换行符)。
优点:
- 使用功能概念,明确您的意图
- 同样,不需要大的缓冲区
缺点:
- 在这种方法中,读/写也没有分开
- 还有更好的方法可以做到这一点,但这应该让你开心。
更新:由于最初的想法需要对BufferedReader
实例进行更复杂的管理,因此我更新了答案以直接在方法中使用行流。