logo
down
shadow

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


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

By : user2186234
Date : November 24 2020, 04:01 AM
I hope this helps . So I have worked out quite a detour solution. I understand that anything in the for-loop wasn't getting written in the file, and I have no idea why the content was not appended to the file.
The solution: First, in the loop, I write the content to a Hashmap and then outside the for-loop write the Hashmap to the file using serialization. It worked perfectly fine.
code :
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();
    }
}}


Share : facebook icon twitter icon
why is bufferedwriter not writing in the file?

why is bufferedwriter not writing in the file?


By : DMorg
Date : March 29 2020, 07:55 AM
hop of those help? You are creating the FileWritter inside the loop so you will always truncate the file in each cycle. You forgot to close / flush the writter But with some luck (terminating the program may cause the writter to flush) the file would contain the last word of your input file which I can only guess would be a new line and you probably missed when you opened up the file to check the content.
Your inner loop should be something like this:
code :
try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"))) {
    while (st.hasMoreTokens()) {
        bw.write(st.nextToken());
        bw.newLine();
    }
}
BufferedWriter not writing to text file

BufferedWriter not writing to text file


By : shy_azusa
Date : March 29 2020, 07:55 AM
it helps some times So I'm using a BufferedWriter and would like to write some text to a text file. , You need to close BufferedWriter, or use try-with-resource
code :
BufferedWriter b = new BufferedWriter(
new FileWriter ("/home/usr/Desktop/logger/logs.txt"));
b.write("hello");

//After writing close the resource
b.close();
BufferedWriter not writing to file

BufferedWriter not writing to file


By : Supratik Bhattachary
Date : March 29 2020, 07:55 AM
should help you out It probably writes to a file, but not the one you think. Java will write to the peopleIDs.txt file in the current directory. The current directory is the directory from which the java command is executed.
If you launch the program from your IDE, check the run configuration to see which current directory it uses. If you really don't know, then search for peopleIDs.txt on your hard drive to find out.
Why is BufferedWriter not writing to file?

Why is BufferedWriter not writing to file?


By : Fernando Andrade Ada
Date : March 29 2020, 07:55 AM
Any of those help Call bWriter.flush() when you want your data to actually be flushed to your file on disk. Or just call bWriter.close() when you're done working with your writer. The bWriter.close() call will call bWriter.flush() internally.
Writing an Integer in file with BufferedWriter

Writing an Integer in file with BufferedWriter


By : user3696410
Date : March 29 2020, 07:55 AM
To fix this issue What happened, when you wrote the int without converting it into a String is, it simply wrote the int as the type it is (an int). So invoking the method e.g. as follows:
code :
writeFile(new int[] {1, 2, 3})
03 00 01 02
Related Posts Related Posts :
  • How do I make this image larger?
  • Run icCube with JDK 10
  • Expression with Math.random() always returns the same value
  • Getting the Set with the most elements nested in a HashMap using Java Streams
  • XmlSlurper to parse XML and get value of inside elements using Groovy
  • Extracting data from HTML and formatting the output
  • SOLR documentCache JMX metrics clarification
  • Limiting Wildfly 14 Two-Way SSL to specific clients
  • How do I get Min and max values to only print when "year" is entered?
  • Hashmap can't loop - getKey() method not found - Using Java 8
  • Android Studio - Create an EditText with a click of a button
  • Mockito Test not invoking verify() method
  • Wrap method implementations of Java interfaces
  • Remediating dynamic SQL into prepared statements
  • Where do X and Y start at in swing windows
  • java code with files work from eclipse but dont work from cmd
  • Return page object from JPA query
  • I can't figure out why this code in my APCS multiple choice book returns 19
  • How to save data between methods
  • I'm trying to install Apache Gobblin. How can I install it using Gradle?
  • Spring Data Sorting Array or Set into Pageable
  • Question about the Java documentation and its implementation
  • How to make a JButton that when pressed it does a new action
  • Java hibernate No validator could be found for boolean
  • Making a POJO Thread Safe
  • Save the data of a text file in a arraylist
  • Sort a List<String[]> by indices using Comparator
  • Overloading in Java for user input?
  • Unable to format timestamp as YYYY-MM-DD HH:mm:ss in java
  • Access SQLite Helper From Adapter
  • How to stream a csv file with header to a HashMap<String, Double> in Java?
  • can't get go daddy ssl certificate to work with spring boot
  • ResourceBundle can't find BaseName gradle project java
  • Java; Jackson; Parsing the array of array json string
  • Java - map key lookup ignoring case
  • Jackson deserialize map null values to empty string
  • Anyone knows why setCount() is not working in twitter4j?
  • Object Visibility in a Multi-threaded Program in Java
  • Can't store and load an arraylist in an object file
  • convert a string number starts with `00` to `+` in java
  • Java - avoiding NonSuchElementException using ConcurrentLinkedDeque
  • Converting Immutable to mutable list Java
  • Getting nosuchmethod exception
  • How to get MQTT subscriptions
  • Android Google Sign in Exceptions
  • JavaFX - method that waits for user input
  • Replacing values for a particular key in treemap changes values for every key
  • This method call passes a null value for a nonnull method parameter. Either the parameter is annotated as a parameter th
  • Kafka: consume all messages on demand
  • Notify what text was changed in textview
  • Tinkerpop/Gremlin: select vertices together with outgoing edge count
  • transform a list of objects into a list of integers that pass a check
  • Why this java code is showing strange behavior?
  • Maven Project classes not compiling
  • Edit image to make text more clear opencv
  • Android Spinner nullpointer
  • Add result to int array every time you finish counting the occurrence
  • Android import java library
  • How to use LDAP Authentication in a corporate environment
  • adding item during iteration in java special usecase
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org