簡體   English   中英

將輸出寫入文本文件

[英]Writing the output to a text file

我想將以下輸出寫入文本文件。 我知道這很容易,但我想我在這里忘記了一些基礎知識。

我嘗試使用“ BufferedWriter”,但找不到變量輸出傳遞給編寫器。 有人可以幫忙嗎?

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;
    }


}

修改您的代碼,如下所示:

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();

您需要的一切都在這里: 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) {
}

檢出java.io.FileWriter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM