Java (Read and write to file)

Java (Read and write to file)

By : CPelote
Date : October 28 2020, 08:00 PM
like below fixes the issue The PrintWriter only really writes when they are closed (close) or flushed (flush or maybe when it thinks it is time ;-)).
Try to use try-with-resources whenever possible, that way you do not need to think about closing/flushing a stream or writer. try-with-resources takes care that AutoClosable-implementations are closed automatically at the end of the try-block.
code :
  Scanner file = new Scanner(new File("Names.txt"));
  PrintWriter pass = new PrintWriter("pass.txt");
  PrintWriter fail = new PrintWriter("fail.txt")
) {

Share : facebook icon twitter icon
JAVA : read and write a file together

JAVA : read and write a file together

By : Pam Grijalva
Date : March 29 2020, 07:55 AM
I wish this help you It's far easier if you don't do two things at the same time. The best way is to run through the entire file, count all the occurrences of each string in a hash and then write out all the results into another file. Then if you need to, move the new file over the old one.
You never want to read and write to the same file at the same time. Your offsets within the file will shift everytime you make a write and the read cursor will not keep track of that.
Java application cannot write/read serialization file when installed to C:/Program Files - java.io.FileNotFoundException

Java application cannot write/read serialization file when installed to C:/Program Files - java.io.FileNotFoundException

By : David Whitten
Date : March 29 2020, 07:55 AM
it helps some times My solution was to use environment variables to get the correct directory to store application data. Here's the method I created:
code :
private String getAppDataDirectory(String subDirectory, boolean create) {

    String appDataDirectory;
    try {
        appDataDirectory = System.getenv("APPDATA"); //Windows
        //todo - could try "ALLUSERSPROFILE"
        if (appDataDirectory != null) {
            appDataDirectory += File.separator + subDirectory + File.separator;
        else { //appDataDirectory is null
            appDataDirectory = System.getenv("HOME"); //Unix
            if (appDataDirectory != null) {
                appDataDirectory +=  File.separator + subDirectory + File.separator;
            else { //appDataDirectory is still null
                throw new Exception("Could not access APPDATA or HOME environment variables");
    catch(Exception e) {
        appDataDirectory = "";

    if (create && appDataDirectory != null && appDataDirectory.length() > 0) {
        try {
            File dir = new File(appDataDirectory);
        catch(Exception e) {

    //log("appDataDirectory: " + appDataDirectory);
    return appDataDirectory;
JAVA-Read a file in java and write them into n different files based on unique words

JAVA-Read a file in java and write them into n different files based on unique words

By : Ionis Keno
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You can look String.split(String regex) and after you split the lines into ArrayLists, then you can control everything you want.
String Split
Write a java program to read from a lengthy string (using streams) and write the output to a file?

Write a java program to read from a lengthy string (using streams) and write the output to a file?

By : Maria Yu
Date : March 29 2020, 07:55 AM
help you fix your problem How can I get a lengthy String as an input using streams and how to write the output to a file ?
code :

Here is another way you can perform the storage.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteExample {
public static void main(String[] args) {

    FileOutputStream fop = null;
    File file;
    String content = "This is the text content";//our you can take it

    try {

        file = new File("c:/newfile.txt");//File creation at C:/
        fop = new FileOutputStream(file);

        // if file doesnt exists, then create it
        if (!file.exists()) {

        // get the content in bytes
        byte[] contentInBytes = content.getBytes();


    } catch (IOException e) {
Read and Write CSV File using Java

Read and Write CSV File using Java

By : Cyrus
Date : March 29 2020, 07:55 AM
hope this fix your issue Create a class to store the header values, and store it in the list. Iterate over the list to save the results.
The currently used map can only store 2 values (which it is storing the header value (name its corresponding value)
code :
    class Headervalues {
    String[] header = new String[3];

public void readLogFile() throws Exception
    List<HeaderValues> list = new ArrayList<>();
    String currentLine = "";
    BufferedReader reader = new BufferedReader(new FileReader(file(false)));
    while ((currentLine = reader.readLine()) != null)
        if (currentLine.contains("2016") && currentLine.contains("helloworld"))

                String nextBlock = replaceAll(currentLine.substring(22, currentLine.length());

                String[] data = nextBlock.split(";");
                HeaderValues headerValues = new HeaderValues();
                //Assuming data.length will always be 3.
                for (int i = 0, max = data.length; i < max; i++)
                    String[] d = data[i].split("=");
                    //Assuming split will always have size 2
                   headerValues.header[i] = d[1];
public void writeContentToCsv() throws Exception
    FileWriter writer = new FileWriter(".../file_new.csv");
    for (HeaderValues value : headerValues)
Related Posts Related Posts :
  • Java - JPA - Generators - @SequenceGenerator
  • What's a good Java-based Master-Slave communication mechanism?
  • Design Help/Suggestion required
  • NullPointerException in com.sun.tools.jxc.SchemaGenTask
  • time required to finish the multithreaded program?
  • Traditional IO vs memory-mapped
  • Using StringBuilder to process csv files to save heap space
  • Response Time is different for mulitiple execution of the application with the same request Performance problem
  • Java - Weblogic - JMX : request available free memory on all servers
  • Error: Can't find common super class of
  • JNI problem when calling a native library that loads another native library
  • calling Stanford POS Tagger maxentTagger from java program
  • Notification framework for java
  • hide keyboard in android?
  • Alternative of JPA
  • How to get Java XP Look and Feel
  • Remote JMS connection still using localhost
  • Java NoClassDefFoundError
  • Is O(N!*N) an acceptable big oh complexity class or do I remove the constant and just say O(N!)?
  • Java File URI error?
  • Using an interface as a constructor parameter in Java?
  • Add additional path to exec-maven-plugin
  • Natural Language parsing of an appointment?
  • Java: How to tell which fontconfig file my system is currently using?
  • How to create notification icon badge on Android apps (like iPhone)
  • Interfaces with hibernate annotations
  • Getting ConnectionTimeoutException with the host did not accept the connection within timeout
  • How to get all property names of a Groovy class?
  • Java Netscape LDAP Remove One Attribute
  • A simple two column layout with Swing
  • Making a Linked list using Generics
  • how to handle result set data
  • Cloning java ArrayList and preventing it from modifications
  • Java How to call method of grand parents?
  • running jython bytecode using java
  • get content from website with utf8 format
  • Sendgrid v3: "Substitutions may not be used with dynamic templating"
  • Application freezes when running method
  • Maven versioning using git branches
  • does a Java getter incur a performance penalty
  • Open Source Implementation of Checkers
  • How can I make a resizable array in Java?
  • Change size of ImageIcon in a JRadioButton
  • Java memory mapped files and swap
  • JAXB Annotated class - setting of a variable which is not an element
  • JSF don't find component in view root with the form id
  • Using Mockito, how do I match against the key-value pair of a map?
  • How do I run my application as superuser from Eclipse?
  • Spring-Security: Call method after authentication
  • How can I add a password to this JDBC:ODBC connection string that is trying to connect to an MS Access database
  • java.sql.SQLException: database locked
  • Json Jackson deserialization without inner classes
  • Error starting modern compiler
  • Generate a random number in interval [0,360) which is divisible by number 15
  • Rotate watermark text at 45 degree angle across the center Apache PDFBox
  • Generate Random number in a range with no repeatation
  • Starting HBASE, java.lang.ClassNotFoundException: org.apache.htrace.SamplerBuilder
  • Using getter and setter methods inside a class in my main class
  • java: <identifier> expected with ArrayList
  • Java Reflection, java.lang.IllegalAccessException Error
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk