I would like to write the following output in to text file. I know it is easy but i think i forget some basics here.
I tried using 'BufferedWriter' but I cant find the variable output to pass to the w开发者_Go百科riter. Can anyone help?
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.regex.Pattern;
/**
* Example program to list links from a URL.
*/
public class SimpleWebCrawler {
public static void main(String[] args) throws IOException {
Validate.isTrue(args.length == 0, "usage: supply url to fetch");
String url = "http://www.placeofjo.blogspot.com/";
print("Fetching %s...", url);
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
System.out.println("\n");
for (Element link : links) {
print(" %s ", link.attr("abs:href"), trim(link.text(), 35));
}
}
private static void print(String msg, Object... args) {
System.out.println(String.format(msg, args));
}
private static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width-1) + ".";
else
return s;
}
}
Modify your code to be like this:
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/path/to/file/name.txt")));
for (Element link : links) {
bw.write("Link: " link.text().trim());
bw.write(System.getProperty("line.separator"));
}
bw.flush();
bw.close();
Everything you need is here : http://www.exampledepot.com/egs/java.io/WriteToFile.html
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
}
Check out java.io.FileWriter
精彩评论