try {
File file = new File("sample.txt");
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
fw.close();
} catch(IOException exp) {
exp.printStackTrace();
}
I am unable to append or write anything to the file.
But I could read the content from the file.
Is anything wrong with my code?
It sounds like you probably are writing to a file - but not the file you expect to. If no exceptions have been thrown (and swallowing an exception, just writing it to standard out, is rarely the right approach) then the file will exist somewhere.
It will be in whatever directory the code is running from - which may well not be the same as the directory containing the sample.txt file you're reading. I suggest you explore the file system, and also check the Run Configuration in Eclipse to see what the working directory for the app will be.
As an aside, you should be closing the writer in a finally block so that it gets closed even if there's an exception, like this:
File file = new File("sample.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file, true);
fw.append('d');
fw.write(100);
} catch(IOException) {
// Ideally do something to indicate the failure to the caller
// - do you need to catch this at all?
e.printStackTrace();
} finally {
// From Guava
Closeables.closeQuietly(fw);
}
Obviously you can do this without Guava but it'll make things a lot simpler - and not just here. If you're using Java 7 you can make it even simpler with a try-with-resources statement.
http://www.roseindia.net/java/example/java/io/java-write-to-file.shtml
You can Flush context if code is right and still you are facing problem. it "Flushes the stream"
This link can help!
Like was said before the file may be getting cleared out during the build/clean process. Try specificing an absolute path to the file and running it again. Everything you have written is correct sans the corrections already offered.
try {
File file = new File("C:\sample.txt"); // for Windows or possibly just "/sample.txt" for *nix
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
} catch(IOException e) {
e.printStackTrace();
} finally {
// Good practice to move close to a finally block
fw.close();
}
You may try using the below syntax :
String filename = "C:/sample.txt";
FileWriter fw = new FileWriter(filename,true);
Related
I have next function:
static void write()
{
try {
File file = new File ("flip.out");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(sMax);
System.out.println(sMax);//This command it works
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is that my program doesn't write anything in my file.
Few things to rectify -
Why create two different instances of File object
File file = new File ("flip.out");
BufferedWriter out = new BufferedWriter(new FileWriter("flip.out"));
All you need to do is
File file = new File ("flip.out");
BufferedWriter out = new BufferedWriter(new FileWriterfile(file ) ));
Next put your close call in finally statement rather than try block. Why? Because of IOException occurs resource will not be closed and if resource do not get closed your changes may not be reflected in the file.
Next it is a good programming practice not to catch Runtime exceptions. So do not use Exception as a ploymorphic type to catch your exception. Use whatever is being thrown like IOException in your case.
Now there might be various reasons why noting is being written in the file. As you are not getting and Exception one of the reason why this might be happening because your static function is not getting called or the string/object sMax(whatever that is) is empty.
Also the file(if not already present) will be created in the current directory. So if there are multiple instance is your code where your are creating files with same name then make sure you are checking the right one.
You have to flush the stream in order for what's in the memory to get written to the drive. What you wrote to BufferedWriter is sitting in a byte array waiting for the rest of it to be filled up before actually writing it to the disk. This helps with performance, but means you have to flush the stream in case you don't fill up that buffer. Here is how you do that:
static void write() throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("flip.out"));
try {
out.write(sMax);
out.flush();
} catch (Exception e) {
// probably could ditch this and
// just the exception bubble up and
// handle it higher up.
e.printStackTrace();
} finally {
out.close();
}
}
So if it makes it to the flush() we know we wrote everything to the stream we wanted. However, if we ever get an exception we make sure we close the stream regardless of success or exception. And finally our stream is outside the try statement because the only exception ever thrown by Writers/OutputStreams during construction is FileNotFoundException which means the file never got opened in the first place so we don't have to close it.
can you call out.flush() before closing.
that will make sure any content in buffer is written to file immediately.
Well, I am trying to write a line of information to log in a text file (.txt) but this is the part where the code fails to write. Everything else works, except this but doesn't give any errors.
public void writeConfig(File config, Boolean append, String errored){
try {
Writer output;
if (config != null){
output = new BufferedWriter(new FileWriter(config));
} else {
output = new BufferedWriter(new FileWriter(er));
}
if (append == true){
output.append(errored);
} else {
output.write(errored);
}
} catch (Exception e){
try {
loadErrorLog(error, true, "Failed to write to Boom's Log.\n");
} catch (Exception e1){
log.info("Major Malfunction #686 : Tell Maker immediatly.");
}
}
}
You're not closing the writer, which means all the data is just staying in the buffer.
You should close it in a finally block.
Additionally:
your use of the append parameter is distinctly dodgy - you should almost certainly be passing it to the constructor of the FileWriter (or FileOutputStream). I don't think append in Writer does what you think it does.
Try to avoid comparing with true - just if (append) would have been clearer
Using the conditional operator could make your FileWriter code cleaner, especially if you used it just for the file:
File file = config == null ? er : config;
Writer writer = new BufferedWriter(new FileWriter(file));
I would avoid using FileWriter in the first place, as it always uses the platform default encoding. Use a FileOutputStream wrapped in an OutputStreamWriter instead, specifying the encoding explicitly (e.g. UTF-8)
Avoid catching Exception in most places; here it would be cleaner to just catch IOException.
It looks like your loadErrorLog method should probably be doing that logging on failure, otherwise I suspect you'll be writing that block of code every time you call it.
Do you really want to continue if you fail to write the config? Is it definitely this method which should handle the exception? I'd potentially remove the catch block entirely (leaving just a try/finally) and let the IOException bubble up the stack
I am trying to create a file and keep on appending into that file. In my code file is getting created but It is not appending anything in that file. Don't know why? Can anyone suggest me what wrong I am doing..
Updated Code:-
File file =new File("D://GeoData1.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
int j = -1;
while(true) {
j++;
String ipAddress = generateIPAddress(j);
try {
out.write(ipAddress);
System.out.println(ipAddress);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should close the file or flush buffers I guess.
Are you closing the writer?
finally {
bufferWritter.close();
}
Update:
If you are using Java 7, try this:
final int NUMBER_OF_IPS_TO_APPEND = 5000; // or whatever size
Charset charset = Charset.defaultCharset();
Path file = Paths.get("myfile.txt");
try (BufferedWriter writer = Files.newBufferedWriter(file, charset,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND)) {
for (int i = 1; i <= NUMBER_OF_IPS_TO_APPEND; i++) {
String ip = generateIPAddress(i);
System.out.printf("Generated ip: %s\n", ip);
writer.append(ip + "\n");
}
} catch (IOException x) {
System.err.format("IOException: %s\n", x);
}
Code adapted from The Java Tutorials.
Check if the IPS are being printed to the console and the file.
Fully working code with a mock implementation of generateIPAddress. It appends 5000 random IPv4 addresses (not checking for validity) to myfile.txt everytime it is executed.
I would try just passing the file writer the file object and getting rid of the .getName()
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
You have infinite loop with while(true). You should make a break point with a statemant or make the the "while" loop like while(i < xy)....
First of all, the loop is never-ending. You should at least make it stop at some point.
Also, you need to close the file to free any memory. Hope it helps!
--edit--
To close a file, its
file.close();
If you want to see the changes made to the file during the time the program is running you need to flush the writer. Please note that sooner or later it will be flushed automatically. The reason why you don't see changes in your text editor depends on your editor. For instance it is not able to open such big file (please note that in your program you are appending chars to this file very fast). Check the size of the file. If the size is increasing then it works.
If you want to monitor the file you can use tools like tail.
I'm trying to export data into a CSV file through Java and I've got some code to do it but it doesn't seem to be outputting the CSV file. Could someone tell me what's wrong? What I would like to do is rather than saving the file somewhere, I would like it to be directly exported to the user.
EDIT: Just in case it's not clear, I don't want the file to be saved anywhere but would like it to be outputted automatically to the user i.e. they click export and get the "Run/Save results.csv" window and they open the file. Currently the file is getting saved so I know that the method seems to work, just in the opposite way that I want it to.
public static void writeToCSV(List<Map> objectList) {
String CSV_SEPARATOR = ",";
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("results.csv"), "UTF-8"));
for (Map objectDetails : objectList) {
StringBuffer oneLine = new StringBuffer();
Iterator it = objectDetails.values().iterator();
while (it.hasNext()) {
Object value = it.next();
if(value !=null){
oneLine.append(value.toString());
}
if (it.hasNext()) {
oneLine.append(CSV_SEPARATOR);
}
}
bw.write(oneLine.toString());
bw.newLine();
}
bw.flush();
bw.close();
} catch (UnsupportedEncodingException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
I would recommend using a framework like opencsv for that. It also does escaping and quoting for you.
If you're not getting errors, check the directory where your code is. Without a specific path, your file is being saved there.
EDIT: Since the file is being saved and you want it to open automatically, use
Runtime.getRuntime().exec("results.csv");
(For Windows - opens the csv file in the default application for csv files)
Runtime.getRuntime().exec("open results.csv");
(For Mac - opens the csv file in the default application for csv files)
recommend HSSFWorkbook to easily read and write excel files.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html
To do that, the CSV reader need to read the memory of your program. This is a little complex thing to do. So, save the file in a temp folder instead. There is no problem to do this sort of thing.
I'm having a problem writing to a file:
FileInputStream fin;
try
{
fin = new FileInputStream ("c:/text.txt");
PrintStream p = new PrintStream(fin);
p.println ("test");
fin.close();
}
catch (IOException ioe)
{
System.err.println (ioe.getMessage);
}
Is there a problem with this code?
You need to use a FileOutputStream.
Get used to the following structure. You'll use it a lot in Java.
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("c:/text.txt"));
out.println ("test");
} catch (IOException e) {
System.err.println (e.getMessage);
} finally {
if (out != null) {
try { out.close(): } catch (Exception e) { }
}
out = null; // safe but not strictly necessary unless you reuse fin in the same scope
}
At least until ARM blocks hopefully eventuate in Java 7.
As noted, you should close the PrintStream and not the FileOutputStream so the above is a better form to use.
Problems with that code that immediately strike me:
Non-standard formatting.
Awkward variable names.
The exception handling is not good.
Failure to close the file in the case of exceptions. (Use acquire(); try { use(); } finally { release(); }.
Hidden use of default character encoding.
PrintStream swallows exceptions. BufferedOutputStream is better.
Failure to flush the decorator. It may still have data buffered. Although actually in this case you have left the PrintStream in auto-flush mode, which can be a performance issue.
Use / for a Windows path separator. You might be able to get away with it, but it's not good.
So:
FileOutputStream fileOut = new FileOutputStream(
"c:\\text.txt"
);
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
fileOut,
"UTF-8" // Or, say, Charset.defaultCharset()
));
out.write("test");
out.newLine()
out.flush();
} finally {
fileOut.close();
}
The class: FileInputStream is used to read input from a file. If you want to write to the file, you can use: FileOutputStream. If you want to make your life really easy, you can use a BufferedOutputStream as well.
As pointed out, you should close your streams in the finally block. The reason why you want to do that is say your program isn't really small, and it's a larger application. If you forget to close file streams, for example, the application will hold on to it and if you try to do something to it on the file system (read: at least in Windows) you won't be able to it. We've all seen the 'File cannot be deleted because it's still in use' error.
Here's an example of using the FileOutputStream + BufferedOutputStream: http://www.javadb.com/write-to-file-using-bufferedoutputstream.