java write data to file without erasing the old content - java

how can i
write data to file without erasing the old content

Use new FileOutputStream(file, true). This will open file in "append" mode which will append all data written to the stream to the end of that file.

You mean "how do you append to a file"? Look for an [append-version of a constructor][1] of your File writing class, e.g.:
public FileWriter(String fileName,
boolean append)
throws IOException
Use this constructor and pass true for the append parameter.
[1]: http://download.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)

if you used the new one in Java 7, you can use this way
try (BufferedWriter writer = Files.newBufferedWriter(outFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND))

in this code i use append (true) but my old date erase and new data overwrite on it please give me solution on it
public class FileOperation {
private static FileReader fileReader;
private static FileWriter fileWriter;
private static BufferedReader bufferedReader;
private static BufferedWriter bufferedWriter;
private static PrintWriter writer;
public static File file = new File("C:\\StudentInfo\\com\\education\\students\\file\\managing\\v1_0\\Student.txt");
public FileOperation() throws IOException {
fileReader = new FileReader(file);
fileWriter = new FileWriter(file, true);
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
// FileOperation fo =new FileOperation();
}
public boolean enrollSudnents(ArrayList<Student> studentList) {
try {
writer = new PrintWriter(file);
writer.print("");
bufferedWriter = new BufferedWriter(new FileWriter(file));
for (Student s : studentList) {
String nameNumberString = String.valueOf(s.getRoll() + "!" + s.getFirstName() + "!" + s.getLastName()
+ "!" + s.getClassName() + "!" + s.getAddress() + "\n");
bufferedWriter.write(nameNumberString);
}
return true;
} catch (Exception e) {
return false;
} finally {
try {
bufferedWriter.close();
fileWriter.close();
} catch (Exception e) {
// logger.info("Exception Found In Adding data");
}
}
}

Related

Writing order string into text file

This is only write "test 2" in the text file.
How to write the first line will be "test 1", and the second line will be "test 2" in the text file.
if(s1.equals("test 1")&&s2.equals("test 2")){
WriteNameOrderInFile.nameOfFirstOrderForImage(s1);
WriteNameOrderInFile.nameOfSecondOrderForImage(s2);
WriteNameOrderInFile class:
public class WriteNameOrderInFile(){
public static void nameOfFirstOrder(String s) throws IOException {
String nameFileDoctor="C:/append info.txt";
FileOutputStream fos = new FileOutputStream(nameFileDoctor);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
}
public static void nameOfSecondOrder(String s) throws IOException {
File file= new File("C:/append info.txt");
FileOutputStream fos2= new FileOutputStream(file,true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos2));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
}
Even if the solution is only to call the correct methods, here are some improvements for your code:
public class WriteNameOrderInFile {
public static void writeToFile(String text, boolean append) {
File file = new File("C:/append info.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, append))) {
bw.write(text);
bw.newLine();
} catch (IOException e) {
// do some exception handling
System.err.println("Can't write to file!");
}
}
public static void main(String[] args) {
// just a sample call with the code you provided
String s1 = "test 1";
String s2 = "test 2";
if (s1.equals("test 1") && s2.equals("test 2")) {
writeToFile(s1, false); // boolean is false, so write (replace) text
writeToFile(s2, true); // append is true, so append text
}
}
}
Some explanations to the improvements of the code:
Your two methods are only different on writing text to a file and appending text to a file. So consider using one method writeToFile and give it an append-boolean
Instead of OutputStreamWriter and FileOutputStream consider using FileWriter
If you're using Java with version >= 7, use try-with-resource statement. You can easily get rid of trying to close streams in a good manner.
BufferedWriter.flush() is also not needed, since it will be done while closing the file (what is done by the try-with-resource statement)

File read, changed but how to write out?

Ok, forgive my beginner-ness and please tell me how I can output my text from "before.txt" into a fresh new file called "after". Obviously I have altered the text along the way to make it lower-case and eliminate non alphabetic characters.
import java.io.*;
public class TextReader {
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile() throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write("before.txt");
output.close();
}
}
What about this
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
writeFile(currentLine);
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile(String text) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write(text);
output.close();
}
}
Let me guess, is this a school assignment?
Try this:
public void ReadAndWrite() throws IOException {
try {
// Read in the file
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine;
while((currentLine = br.readLine()) != NULL){
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
output.write(currentLine);
}
br.close(); // Close br to prevent resource leak
output.close();
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}

Writing to multiple files without duplicating code Java

I have this code to write to a file when I add a user to an array list. The code works fine:
public void writeToFile(String content)
{
try {
File file = new File("H:/JavaWorkspace/TradingPlatformProject/User_Report.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
I want to write to a separate file when a user does something differently (say, request a permission upgrade). Is there any way I can write to a new file "UserRequests.txt" without duplicating this code?
Why not make the method more general?
public void writeToFile(String content, String fileName, String path)
{
try {
File file = new File(path + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
Then you could use the method for writing all kinds of files :3
You should probably just use a 2nd argument, as in the following.
Moreover, you should close your Writers in a finally block. That way, you would be sure that the Writers are closed even if a exception occurred while writing.
public void writeToFile(String content, String path)
{
FileWriter fw
BufferedWriter bw
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
} finally {
bw.close();
fw.close();
}
}
I would just pass in the file you want to write to:
public void writeToFile(String content, String filename){
And then:
File file = new File("H:/JavaWorkspace/TradingPlatformProject/"+filename);

Howto save HashSet<String> to .txt?

I want to store the HashSet to the server directory.
But i'm now only been able to store it in .bin files.
But how do I print all the Key's in the HashSet to a .txt file?
static Set<String> MapLocation = new HashSet<String>();
try {
SLAPI.save(MapLocation, "MapLocation.bin");
} catch (Exception ex) {
}
public static void save(Object obj, String path) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
path));
oos.writeObject(obj);
oos.flush();
oos.close();
}
// check IOException in method signature
BufferedWriter out = new BufferedWriter(new FileWriter(path));
Iterator it = MapLocation.iterator(); // why capital "M"?
while(it.hasNext()) {
out.write(it.next());
out.newLine();
}
out.close();
This will save the strings to a UTF-8 text file:
public static void save(Set<String> obj, String path) throws Exception {
PrintWriter pw = null;
try {
pw = new PrintWriter(
new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
for (String s : obj) {
pw.println(s);
}
pw.flush();
} finally {
pw.close();
}
}
Specifically choosing UTF-8 is desirable because otherwise it will use whatever setting the operating system uses as its default, which will give you compatibility headaches.
Something like this:
public static void toTextFile(String fileName, Set<String> set){
Charset charset = Charset.forName("UTF-8");
try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(fileName, charset))) {
for(String content: set){
writer.println(content);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
}
Note: This code is written using the try-with-resource construct introduced in Java 7. But the idea would remain the same for other versions as well.
Another solution that avoids a line break at the end of the file:
private static void store(Set<String> sourceSet, String targetFileName) throws IOException
{
StringBuilder stringBuilder = new StringBuilder();
for (String setElement : sourceSet)
{
stringBuilder.append(setElement);
stringBuilder.append(System.lineSeparator());
}
String setString = stringBuilder.toString().trim();
byte[] setBytes = setString.getBytes(StandardCharsets.UTF_8);
Files.write(Paths.get(targetFileName), setBytes);
}

This program neither reads nor writes to a file

CODE
import java.io.*;
class tester {
public static void main(String args[]) {
try {
FileReader reader = new FileReader(new File("d:\\UnderTest\\check123.txt"));
FileWriter writer = new FileWriter(new File("d:\\UnderTest\\check123.txt"));
BufferedReader br = new BufferedReader(reader);
String s;
while( (s=br.readLine()) != null ) {
System.out.println(s);
}
writer.write("Shadow Shadow");
} catch(Exception exc) {
System.out.println(exc);
}
}
}
This code writes nothing and reads nothing when i run it. Where is the bug in this program ?
Are you sure that when you read for first time then content is there in the text file ?
You need to close Reader and Writer in finally block (missing currently in your code) of your try-catch block. closing the stream flushes out content automatically.
Make sure you close the reader and the writer. After using the writer you will need to flush the contents or close the writer (which does the same thing). I tested this and it works.
import java.io.*;
class tester {
public static void main(String args[]) {
try {
FileReader reader = new FileReader(new File("c:\\check123.txt"));
FileWriter writer = new FileWriter(new File("c:\\check123.txt"));
BufferedReader br = new BufferedReader(reader);
writer.write("Shadow Shadow");
writer.close();
String s;
while( (s=br.readLine()) != null ) {
System.out.println(s);
}
reader.close();
} catch(Exception exc) {
System.out.println(exc);
}
}
}

Categories

Resources