When it comes to Java local storage, you definitely use IO streams for operations.
First, we need a function to create the file CreateNewFile:
Then we need a function to write to the file:
Copy Code code as follows:
public static Boolean Writeintofile (string content, String FilePath,
Boolean isappend) {
Boolean issuccess = true;
Filter out file names first
int index = Filepath.lastindexof ("/");
String dir = filepath.substring (0, index);
To create a path in addition to a file
File Filedir = new file (dir);
Filedir.mkdirs ();
To create a file under a path
File file = null;
try {
File = new file (FilePath);
File.createnewfile ();
catch (IOException e) {
Issuccess = false;
E.printstacktrace ();
}
Write to File
FileWriter FileWriter = null;
try {
FileWriter = new FileWriter (file, isappend);
Filewriter.write (content);
Filewriter.flush ();
catch (IOException e) {
Issuccess = false;
E.printstacktrace ();
finally {
try {
if (fileWriter!= null)
Filewriter.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
return issuccess;
}
We encapsulate these two functions in a Filereaderwriter.java file for subsequent use.
Then we go back to the reptilian.
We need to add a function to the known Zhihu encapsulation class to format the typography written to the local.
Copy Code code as follows:
Public String writestring () {
String result = "";
result = = "question:" + question + "\ r \ n";
result = = "Description:" + questiondescription + "\ r \ n";
result = = "Link:" + zhihuurl + "\ r \ n";
for (int i = 0; i < answers.size (); i++) {
Result + + "answer" + i + ":" + answers.get (i) + "\ r \ n";
}
result = = "\r\n\r\n";
return result;
}
OK, that's about it, then. The System.out.println in the Mian method is changed to
Copy Code code as follows:
Write to Local
for (Zhihu Zhihu:myzhihu) {
Filereaderwriter.writeintofile (Zhihu.writestring (),
"d:/know-edit recommended TXT", true);
}
Run, you can see what was originally seen in the console has been written to the local TXT file:
Generally see no problem, take a closer look at the discovery problem: There are too many HTML tags, mainly <b> and <br>.
We can process these tags when we output them.
First the <br> into IO stream inside the \ r \ n, and then all the HTML tags are deleted, so it will look much clearer.
Copy code code as follows:
Public String writestring () {
Stitching writes to a local string
String result = "";
result = = "question:" + question + "\ r \ n";
result = = "Description:" + questiondescription + "\ r \ n";
result = = "Link:" + zhihuurl + "\ r \ n";
for (int i = 0; i < answers.size (); i++) {
Result + + "answer" + i + ":" + answers.get (i) + "\r\n\r\n";
}
result = = "\r\n\r\n\r\n\r\n";
Filter the HTML tags in them
result = Result.replaceall ("<br>", "\ r \ n");
result = Result.replaceall ("<.*?>", "");
return result;
}
The ReplaceAll function here can use regular, so all the <> tags are deleted at the end.