LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Can not write to file in Java (https://www.linuxquestions.org/questions/programming-9/can-not-write-to-file-in-java-388809/)

irfanhab 12-02-2005 10:58 PM

Can not write to file in Java
 
This program is supposed to read a file of the format:
asdf,asdf,sadf

And write a column into a file called var.txt, but it creates the file, and does not write anything to it. No exception occurs

Code:

import java.io.*;
import java.util.*;

public class colsplit {

 public static void main(String[] args)
 {
 
  Vector<String[]> vs = new Vector<String[]>();
  try
  {
  BufferedReader br = new BufferedReader(new FileReader(args[0]));
 
  while(br.ready())
  {
    StringTokenizer st = new StringTokenizer(br.readLine(),",");
    String[] arr = new String[st.countTokens()];
    for(int i=0;i<=st.countTokens();i++)
    {
    arr[i] = st.nextToken();
    }
    vs.add(arr);
   
  }
 
 
 
  BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/root/var.txt")));
 
  for(int j=0;j<vs.size();j++)
  {
   
    bw.write(vs.elementAt(j)[Integer.parseInt(args[2])]  + "\n");
  }
   
  }catch(Exception e)
  {}
   
}
}


paulsm4 12-02-2005 11:20 PM

Have you considered that maybe "vs" has zero elements?

irfanhab 12-03-2005 01:59 AM

[QUOTEHave you considered that maybe "vs" has zero elements?[/QUOTE]

this is not possible as I intentionally valid data to it,

If I go like:
Code:

for(int i=0;i<vs.size;i++)
{System.out.println(vs.elementAt(i));
}

It does show valid output but never writes it to the file.

ppanyam 12-03-2005 02:59 AM

Can you try bw.flush() after bw.write()?

irfanhab 12-03-2005 03:36 AM

yes ppanyam that worked. thanks!
but when you write shudnt the JVM itself handle the flushing, instead of calling it explicity.

paulsm4 12-03-2005 01:19 PM

Your program is supposed to do an explicit "close()". Which, in turn, does an implicit "flush()".

ppanyam 12-04-2005 11:49 PM

The BufferedWriter "write()"s to buffer, as the name suggests. It will write to disk as per a predefined policy like if buffer is full or if x amount of time has lapsed. If you want it to write immediately to disk, you invoke flush() on the BufferedWriter. Alternately, if you close() the stream, it will clean up and will write to disk.

paulsm4 12-05-2005 12:01 AM

ppanyam is right.

A "BufferedWriter" (by definition!) buffers its data (in the name of I/O efficiency). If you don't like this behavior, you can either flush whenever you wish to, or choose an unbuffered I/O class.

But in any case - you must absolutely "close()" any file you open. Doing otherwise (e.g. depending on the OS or JVM to "clean up after you") is, frankly, just sloppy programming.

IMHO .. PSM


All times are GMT -5. The time now is 09:14 PM.