Here is the code, in which I'm trying to write using Filewriter. This is working fine.
File f2 = new File("Path");
f2.createNewFile();
FileWriter writing = new FileWriter(f2);
writing.write("i'm into you , i'm into you");
writing.flush();
In the following code, I'm trying to write using bufferedwriter. This is not adding any text into the same file. For different file, it is working.
BufferedWriter buffwrite = new BufferedWriter(writing); buffwrite.write("java");
writing.flush();
Yes, definitely you can write both in same class.
Your code is not adding any text into the same file because you are Flushing out FileWriter before BufferedWriter. I just edited your code as below and it worked fine.
File f2 = new File("Path");
f2.createNewFile();
FileWriter writing = new FileWriter(f2);
writing.write("i'm into you , i'm into you");
BufferedWriter buffwrite = new BufferedWriter(writing);
buffwrite.write("java");
buffwrite.flush();//flush BufferedWriter first followed by FileWriter
writing.flush();
You should close the resources your opened: FileWriter writing and BufferedWriter buffwrite. This (JavaDoc)
Flushes the stream. If the stream has saved any characters from the
various write() methods in a buffer, write them immediately to their
intended destination. Then, if that destination is another character
or byte stream, flush it. Thus one flush() invocation will flush all
the buffers in a chain of Writers and OutputStreams.
The right way is to use the try-resource statement. This will tale care to close opened resources.
Or use the java.nio.file.Files.write methods which will do the resource handling.
These IO related classes are designed based on decorator pattern.
If you refer to the BufferedWriter class javadoc, you'd find a constructor that takes a Writer type object. Writer is an abstract class which is extended by FileWriter among other classes. Pass your FileWriter object in the constructor and then call the write (...) and flush methods of BufferedWriter.
All IO classes work in this pattern.
Yes you can write.Please checkout the below usecases for writing file in java using FileWriter, BufferedWriter, FileOutputStream and Files in java.
package com.journaldev.files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WriteFile {
/**
* This class shows how to write file in java
* #param args
* #throws IOException
*/
public static void main(String[] args) {
String data = "I will write this String to File in Java";
int noOfLines = 10000;
writeUsingFileWriter(data);
writeUsingBufferedWriter(data, noOfLines);
writeUsingFiles(data);
writeUsingOutputStream(data);
System.out.println("DONE");
}
/**
* Use Streams when you are dealing with raw data
* #param data
*/
private static void writeUsingOutputStream(String data) {
OutputStream os = null;
try {
os = new FileOutputStream(new File("/Users/pankaj/os.txt"));
os.write(data.getBytes(), 0, data.length());
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Use Files class from Java 1.7 to write files, internally uses OutputStream
* #param data
*/
private static void writeUsingFiles(String data) {
try {
Files.write(Paths.get("/Users/pankaj/files.txt"), data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Use BufferedWriter when number of write operations are more
* It uses internal buffer to reduce real IO operations and saves time
* #param data
* #param noOfLines
*/
private static void writeUsingBufferedWriter(String data, int noOfLines) {
File file = new File("/Users/pankaj/BufferedWriter.txt");
FileWriter fr = null;
BufferedWriter br = null;
String dataWithNewLine=data+System.getProperty("line.separator");
try{
fr = new FileWriter(file);
br = new BufferedWriter(fr);
for(int i = noOfLines; i>0; i--){
br.write(dataWithNewLine);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Use FileWriter when number of write operations are less
* #param data
*/
private static void writeUsingFileWriter(String data) {
File file = new File("/Users/pankaj/FileWriter.txt");
FileWriter fr = null;
try {
fr = new FileWriter(file);
fr.write(data);
} catch (IOException e) {
e.printStackTrace();
}finally{
//close resources
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
I made the program in java to convert the text in the file in the uppercase but it erases data instead of converting it
But when I take data from 1 file and write converted data into another file, it works fine.
So I got problem that how can I do this using single file.
Here below is my code, Tell me how to correct this?
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
public class uppercase{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("e.txt");
FileWriter writer = new FileWriter("e.txt");
int data;
int data2;
while((data=reader.read())!= -1) {
data2=Character.toUpperCase(data);
writer.write(data2);
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is bad idea, because you are writing to same file you are reading from. You should either:
Load complete file to memory, close it and then dump it to same file.
Save to different file and rename (better)
firstly you open a stream to read from file and append the result to a String variable and at the end of reading, you write all the data to the file:
try {
FileReader reader = new FileReader("e.txt");
String result = "";
int data;
int data2;
while ((data = reader.read()) != -1) {
data2 = Character.toUpperCase(data);
result += (char)data2;
}
reader.close();
System.out.println(result);
FileWriter writer = new FileWriter("e.txt");
writer.write(result);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am currently trying to program a small API, but with my writeToFile method, even if I use true in the method, it deletes everything that is in the file and only writes in the text of the user (#param text).
What did I do wrong ? I tried to print the string, but it appears to be empty. If I only use the readFile method of mine, it reads out the whole file correctly.
Need help.
package at.tornaduuu.usefullapi.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileUtils {
public static void writeToFile(String text, File file, boolean keepIndexText) {
try {
String indexText = "";
FileWriter fw = new FileWriter(file);
if (keepIndexText) {
indexText = FileUtils.readFile(file);
System.out.println(indexText);
FileUtils.clearFile(file);
fw.write(indexText + text);
fw.close();
}
else {
fw.write(text);
fw.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void clearFile(File file) {
try {
FileWriter fw = new FileWriter(file);
fw.write("");
fw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static String readFile(File file) {
String fileIndex = "";
int unicode;
try {
FileReader fr = new FileReader(file);
try {
while ((unicode = fr.read()) != -1) {
fileIndex += (char) unicode;
}
fr.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return fileIndex;
}
}
You are not appending to file, you are just rewriting it. That's because FileWriter is not set to append. You can change this:
FileWriter fw = new FileWriter(file); //rewrites file every time write() method is called
to:
FileWriter fw = new FileWriter(file,true); //append text in file when write() is called
and it should work.
You are calling FileWriter(File) which in turn will call FileOutputStream(String name, append = False). So your file is getting truncated before you read content.
There is another constructor FileWriter(File file, boolean append) that you can use with keepIndexText, in such case your FileUtils.clearFile(file); is pretty useless.
These are the contents of the constructor of a class which is called by the main method.
File f = null;
Scanner s;
try {
f = new File(getClass().getResource("/LOL.txt").toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
s = new Scanner(f);
while(s.hasNextLine()) System.out.println(s.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(f.getAbsoluteFile(), false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("LOL");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Output in the console:
LOL
The contents of the file remain unchanged even after repeated runs. My IDE is eclipse
You parametrize your FileWriter with boolean append set as false.
Therefore, the same file will be written over every time that given constructor is executed, and "LOL" will be printed in it.
Before printing "LOL", a Scanner reads each line and prints it, hence the LOL printed in our system out.
Also note, you probably want to declare your FileWriter and BufferedWriter out of the try block, so you can flush and close them in a finally block.
This post only contains the initial question, as-is with everything corrected to avoid several resource-related bugs. It assumes Java 6 or lower.
I shouldn't get any upvote so please don't ;)
package so39452286;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
File file = new File(getClass().getResource("/LOL.txt").toURI());
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
if (scanner != null) {
scanner.close();
}
}
Writer writer = null; // Holds the main resource, not the wrapping ones.
try {
writer = new FileWriter(file.getAbsolutePath(), false);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("LOL");
bw.flush(); // You forgot to flush. Ok, close() does it, but it's always better to be explicit about it.
} finally {
if (writer != null) {
writer.close();
}
}
} catch (Exception e) {
// Do something with e.
e.printStackTrace(System.err);
}
}
}
I really need help with Java io manipulation of Streams. I don't know why this won't show me the contents of the file. I need to be able to view the text in this binary file "Data.abc" If I can view the contents of this file, i need to create a switch case condition to display it's contents per row / column.
Everytime I run the program, it returns some weird letters and characters like � NAme Address�����
Please help. I'm new to manipulation of streams. Thanks.
package IO_ReadFile;
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
InputStream istream; // creates an Input Stream and named it "istream"
OutputStream ostream; // creates an Output Stream and named it "ostream"
File inputFile = new File("Data.abc"); //passes file as argument
int c;
final int EOF=-1;
ostream = System.out;
try
{
istream = new FileInputStream(inputFile);
try
{
while((c=istream.read()) !=EOF)
ostream.write(c);
}
catch(IOException e)
{
System.out.println("Error: " + e.getMessage());
}
finally
{
try
{
istream.close();
ostream.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}
}
catch(FileNotFoundException e)
{
System.exit(1);
}
}
}
I have a java application that needs to write a lot of data into individual lines in a text file. I wrote the code below to do this, but for some reason, it is not writing anything to the text file. It does create the text file, but the text file remains empty after the program is done running. Can anyone show me how to fix the code below so that it actually fills the output file with as many lines of output as it is called upon to do?
public class MyMainClass{
PrintWriter output;
MyMainClass(){
try {output = new PrintWriter("somefile.txt");}
catch (FileNotFoundException e1) {e1.printStackTrace();}
anotherMethod();
}
void anotherMethod(){
output.println("print some variables");
MyOtherClass other = new MyOtherClass();
other.someMethod(this);
}
}
public class MyOtherClass(){
void someMethod(MyMainClass mmc){
mmc.output.println("print some other variables")
}
}
How you are going about doing this seems very strange to me. Why don't you write one method that takes in a string and then writes it to your file? Something like this should work fine
public static void writeToLog(String inString)
{
File f = new File("yourFile.txt");
boolean existsFlag = f.exists();
if(!existsFlag)
{
try {
f.createNewFile();
} catch (IOException e) {
System.out.println("could not create new log file");
e.printStackTrace();
}
}
FileWriter fstream;
try {
fstream = new FileWriter(f, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(inString+"\n");
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("could not write to the file");
e.printStackTrace();
}
return;
}
Use the other constructor:
output = new PrintWriter(new FileWriter("somefile.txt"), true);
According to JavaDoc:
public PrintWriter(Writer out, boolean autoFlush)
Creates a new PrintWriter.
Parameters:
out - A character-output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer
Use other constructor new PrintWriter(new PrintWriter("fileName"), true) for auto-flushing data or
Use flush() and close() when you're done writing