簡體   English   中英

為什么即使我最后關閉它,這里的BufferedWriter也不寫文件?

[英]Why BufferedWriter here is not writing to the file even though I close it in the end?

因此,我編寫了一個在“ for”循環中將字符串寫入文件的類,但是我無法使用Java中的BufferedWriter或PrintWriter將字符串內容寫入文件。 該文件在本地目錄中創建,但是沒有任何內容寫入該文件。 似乎是什么引起了麻煩?

  • 我已經關閉/刷新了BufferedWriter / PrintWriter
  • 要寫入文件的內容會打印在屏幕上,但不會寫入文件。
  • 該命令“追加”到文件,而不是“寫入”(但是,我已經嘗試使用寫入功能,但是沒有用。)

代碼是

package pmidtomeshConverter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Convert2MeSH {

    public static void main(String[] args) throws JSONException, IOException, ParserConfigurationException, SAXException, TransformerException {


    BufferedWriter writer = new BufferedWriter(new FileWriter("pathToALocalDirectory/pmidMESH.txt", true));
    writer.write("at least this writes"); // This does not write either


    JSONObject jsonPMIDlist = readJsonFromUrl("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmode=json&retmax=1000&term=Physiotherapy%5d+OR+Rehabilitation");
    JSONArray pmids = new JSONArray();
    pmids = jsonPMIDlist.getJSONObject("esearchresult").getJSONArray("idlist");

    for(int i=0; i<pmids.length();i++){

        String baseURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id=";

        String indPMID = pmids.get(i).toString();

        Document doc = parseXML(new URL(baseURL + indPMID));

        String xmlString = xml2String(doc);

        // Converts the XML string into JSON
        JSONObject jsonWithMeSH = XML.toJSONObject(xmlString);

        JSONObject ind_MeSH = jsonWithMeSH.getJSONObject("PubmedArticleSet").getJSONObject("PubmedArticle").getJSONObject("MedlineCitation");

        List<String> list_MeSH = new ArrayList<String>();
        if (ind_MeSH.has("MeshHeadingList")) {

            for (int j = 0; j < ind_MeSH.getJSONObject("MeshHeadingList").getJSONArray("MeshHeading").length(); j++) {

                list_MeSH.add(ind_MeSH.getJSONObject("MeshHeadingList").getJSONArray("MeshHeading").getJSONObject(j).getJSONObject("DescriptorName").get("content").toString());
            }

        } else {

            list_MeSH.add("null");

        }

        System.out.println(indPMID + ":" + String.join("\t", list_MeSH));
        writer.append(indPMID + ":" + String.join("\t", list_MeSH)); // This does not write to the file either

    }

    writer.flush();
    writer.close();

}

private static String xml2String(Document doc) throws TransformerException {

    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.METHOD, "xml");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));

    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc.getDocumentElement());

    trans.transform(source, result);
    String xmlString = sw.toString();
    return xmlString;

}

private static Document parseXML(URL url) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse((url).openStream());
    doc.getDocumentElement().normalize();
    return doc;
}

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}

“ System.out.println(indPMID +”:“ + String.join(” \\ t“,list_MeSH));的輸出;” 是,

  • 30541041:空
  • 30541034:空
  • 30541029:空
  • 30541003:空
  • 30540990:空
  • 30540822:空
  • 30540806:空
  • ...

所以我想出了一個繞路的解決方案。 我知道for循環中的任何內容都沒有寫入文件,而且我也不知道為什么內容沒有附加到文件中。

解決方案:首先,在循環中,將內容寫入Hashmap,然后在for循環之外,使用序列化將Hashmap寫入文件。 它工作得很好。

這是代碼,

package pmidtomeshConverter;

import java.io.BufferedReader;      
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Convert2MeSH {

    public static void main(String[] args) {


        //BufferedWriter writer = new BufferedWriter(new FileWriter("/home/anjani/eclipse-workspace/pmidtomeshConverter/src/main/resources/outputFiles/pmidMESH.txt", true));

        //Universal Multimap to store the values
        Map<String, String> universalMeSHMap = new HashMap<String, String>();

        FileOutputStream fs;
        BufferedWriter writer;
        try {

            fs = new FileOutputStream("/home/anjani/eclipse-workspace/pmidtomeshConverter/src/main/resources/outputFiles/pmidMESH.txt");
            OutputStreamWriter ow = new OutputStreamWriter(fs);
            writer = new BufferedWriter(ow);

            JSONObject jsonPMIDlist = readJsonFromUrl("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmode=json&retmax=1000&term=Physiotherapy%5d+OR+Rehabilitation");
            JSONArray pmids = new JSONArray();
            pmids = jsonPMIDlist.getJSONObject("esearchresult").getJSONArray("idlist");

            for(int i=0; i<pmids.length();i++){

                 String baseURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id=";
                 String indPMID = pmids.get(i).toString();

                 Document doc = parseXML(new URL(baseURL + indPMID));

                 // Converts xml from doc into a string
                 String xmlString = xml2String(doc);

                // Converts the xml-string into JSON
                JSONObject jsonWithMeSH = XML.toJSONObject(xmlString);

                JSONObject ind_MeSH = jsonWithMeSH.getJSONObject("PubmedArticleSet").getJSONObject("PubmedArticle").getJSONObject("MedlineCitation");

                List<String> list_MeSH = new ArrayList<String>();
                if (ind_MeSH.has("MeshHeadingList")) {

                for (int j = 0; j < ind_MeSH.getJSONObject("MeshHeadingList").getJSONArray("MeshHeading").length(); j++) {

                    list_MeSH.add(ind_MeSH.getJSONObject("MeshHeadingList").getJSONArray("MeshHeading").getJSONObject(j).getJSONObject("DescriptorName").get("content").toString());
                }

                } else {

                list_MeSH.add("null");

                }

            System.out.println(indPMID + ":" + String.join("\t", list_MeSH));

            // instead of writing to a file, the content is stored in a HashMap
            universalMeSHMap.put(indPMID, String.join("\t", list_MeSH));                

        }

        // Writing the HashMap to the file (This is the answer)
        for (Map.Entry<String,String> entry : universalMeSHMap.entrySet()) {

            writer.append(entry.getKey() + ":" +  entry.getValue() + "\n");

        }

        writer.flush();
        writer.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private static String xml2String(Document doc) throws TransformerException {

    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.METHOD, "xml");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));

    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc.getDocumentElement());

    trans.transform(source, result);
    String xmlString = sw.toString();
    return xmlString;

}

private static Document parseXML(URL url) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse((url).openStream());
    doc.getDocumentElement().normalize();
    return doc;
}

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}}

結果文件看起來像這樣,

內容被寫入文件。 文件中的每一行都包含一個唯一的Pubmed ID,該ID附加在文章的MeSH條款上

暫無
暫無

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

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