How to append to a file in java [duplicate] - java

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 4 years ago.
I open file as follows
private static Formatter x;
public static void openFile(){
try{
x=new Formatter("sarit.text");
}
catch(Exception e){
System.out.println("error");
}
}
Here I add a information to the file but the problem of adding the information to this file erases everything that was in the file before inserting the information
public static void addRecords(String age,String city,String name, String password){
x.format(" "+name+" "+password+" "+age+" "+city+"\n");
}
public static void closeFile(){
x.close();
}

Welcome to StackOverflow!
You are doing new Formatter("sarit.text");
Checking javadoc for
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)
if the file exists then it will be truncated to zero size
you need to append to file.
Question How to append text to an existing file in Java provides answers how to append to file in java.

Assuming you're using java.util.Formatter, the documentation specifically says:
If the file exists then it will be truncated to zero size; otherwise,
a new file will be created
You have to find a different way to do it, with a BufferedWriter for example:
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
The true parameter tells the FileWriter to append to the file.
If you want to use formatting, use String.format():
writer.write(String.format(...));

Related

Read entire File to String Spring Boot [duplicate]

This question already has answers here:
How do I load a resource and use its contents as a string in Spring
(7 answers)
Closed 9 months ago.
I have a text file with path as resources/templates/temp.txt. I tried reading it with built in Files.readAllBytes() function found in java.nio but that results in an NullPointerException. My code looks as follows:
try {
File file = new File(getClass().getResource("templates/temp.txt").getFile());
String temp = new String(Files.readAllBytes(Paths.get(file.getPath())));
System.out.println(temp);
}catch(Exception e){
e.printStackTrace();
}
The file actually does exist at this location because I am able to get an InputStream and use that in an InputStreamReader and BufferedReader to read the file line-by-line.
InputStream input = this.getClass().getClassLoader().getResourceAsStream(path)
//path here is "templates/temp.txt"
I would like to read this file with a built in method rather than iterating over the entire thing.
Would appreciate it very much if someone can help with this. Thanks in advance!
How does your code even compile? You have static reference in non-static env:
... new File(getClass().getResource ...
try to get the bytearray before transforming into string:
try {
byte[] tmpba = Files.readAllBytes(Paths.get("templates/temp.txt"));
String s = new String(tmpba);
System.out.println(s);
}catch(Exception e){
e.printStackTrace();
}

Comments are getting deleted after updating .properties file [duplicate]

This question already has answers here:
Java Properties: How to keep non key=value lines?
(2 answers)
Adding comments in a properties file line by line
(3 answers)
Closed 7 years ago.
I have a .properties file which have number of comments in it, when I try to update the content of the file other than the comments, even though my comments are disappearing, how to retain my comments?
Here is the config.properties file:
#name of user
name=user1
#id of user
id=id1
and the code to update the properties file, I used
public class SetLog {
public static void setPath()
{
File file = new File("./config.properties");
Properties prop = new Properties();
FileInputStream objInput = null;
try {
objInput = new FileInputStream(file);
prop.load(objInput);
objInput.close();
FileOutputStream out = new FileOutputStream("./config.properties");
//update the content
prop.setProperty("name", "user2");
prop.store(out, null);
out.close();
} catch (Exception e) {}
}
}
After I run the above code, properties file content changed to:
name=user2
id=id1
But I want in this format:
#name of user
name=user2
#id of user
id=id1
How to retain my comments, please help!
This has been answered in a similar question: Adding comments in a Property File. Basically it boils down to using the Apache Commons extension to read and write Property Files.
Try to read the characters in the file and ignore those lines beginning with # .
See this link

how do i get the data from a database and store it into a text file?

I am new to databases in Java and i am trying to export the data from 1 table and store it in a text file. At the moment the code below writes to the text file however all on one line? can anyone help?
My Code
private static String listHeader() {
String output = "Id Priority From Label Subject\n";
output += "== ======== ==== ===== =======\n";
return output;
}
public static String Export_Message_Emails() {
String output = listHeader();
output +="\n";
try {
ResultSet res = stmt.executeQuery("SELECT * from messages ORDER BY ID ASC");
while (res.next()) { // there is a result
output += formatListEntry(res);
output +="\n";
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return output;
}
public void exportCode(String File1){
try {
if ("Messages".equals(nameOfFile)){
fw = new FileWriter(f);
//what needs to be written here
//fw.write(MessageData.listAll());
fw.write(MessageData.Export_Message_Emails());
fw.close();
}
}
Don't use a hard coded value of "\n". Instead use System.getProperty("line.separator"); or if you are using Java 7 or greater, you can use System.lineSeparator();
Try String.format("%n") instead "\n".
Unless you're trying to practice your Java programming (which is perfectly fine of course!), you can export all the data from one table and store it in a file by using the SYSCS_UTIL.SYSCS_EXPORT_TABLE system procedure: http://db.apache.org/derby/docs/10.11/ref/rrefexportproc.html
I'm gonna assume you are using Windows and that you are opening your file with notepad. If that is correct then it is not really a problem with your output but with the editor you are viewing it with.
Try a nicer editor, ie. Notepad++
Do as the other answers suggest and use System.getProperty("line.separator"); or similar.
Use a Writer implementation such as, PrintWriter.
Personally I prefer "\n" over the system line separator, which on Windows is "\r\n".
EDIT: Added option 3

Insert a string in the middle of text file without replacing [duplicate]

This question already has answers here:
inserting data in the middle of a text file through java
(2 answers)
Closed 9 years ago.
Suppose i have a text file named Sample.text.
i need advice on how to achieve this:
Sample.txt before running a program:
ABCD
while running the program, user will input string to be added starting at the middle
for example: user input is XXX
Sample.txt after running a program:
ABXXXCD
Basically you've got to rewrite the file, at least from the middle. This isn't a matter of Java - it's a matter of what file systems support.
Typically the way to do this is to open both the input file and an output file, then:
Copy the first part from the input file to the output file
Write the middle section to the output file
Copy the remainder of the input file to the output file
Optionally perform file renaming if you want the new file to have the same eventual name as the original file
The basic idea is to read the file contents into memory, say at program start, manipulate the string as desired, then write the entire thing back to the file.
So you would open and read in Sample.txt. In memory you have a string = "ABCD"
in your program execution, accept user input of XXX. Insert that into your string with your favorite string manipulation method. Now string = "ABXXXCD"
Finally you would overwrite Sample.txt with your updated string and close it.
If you were worried about corruption or something, you might save it to a secondary file, then verify its contents, delete the original, and rename the new to be the same as the original.
Actually i have did something like what you want, here try this code, its not a complete but it should give you a clear idea:
public void addString(String fileContent, String insertData) throws IOException {
String firstPart = getFirstPart(fileContent);
Pattern p = Pattern.compile(firstPart);
Matcher matcher = p.matcher(fileContent);
int end = 0;
boolean matched = matcher.find();
if (matched) {
end = matcher.end();
}
if(matched) {
String secondPart = fileContent.substring(end);
StringBuilder newFileContent = new StringBuilder();
newFileContent.append(firstPart);
newFileContent.append(insertData);
newFileContent.append(secondPart);
writeNewFileContent(newFileContent.toString());
}
}
Normally a new file would be created, but the following probably suffices (for non-gigabyte files). Mind the explicit encoding UTF-8; which you can ommit for the encoding of the operating system.
public static void insertInMidstOfFile(File file, String textToInsert)
throws IOException {
if (!file.exists()) {
throw new FileNotFoundException("File not found: " + file.getPath());
// Because file open mode "rw" would create it.
}
if (textToInsert.isEmpty()) {
return;
}
long fileLength = file.length();
long startPosition = fileLength / 2;
long remainingLength = fileLength - startPosition;
if (remainingLength > Integer.MAX_VALUE) {
throw new IllegalStateException("File too large");
}
byte[] bytesToInsert = textToInsert.getBytes(StandardCharsets.UTF_8);
try (RandomAccessFile fh = new RandomAccessFile(file, "rw")) {
fh.seek(startPosition);
byte[] remainder = new byte[(int)remainingLength];
fh.readFully(remainder);
fh.seek(startPosition);
fh.write(bytesToInsert);
fh.write(remainder);
}
}
Java 7 or higher.

Replacing old content of a text file with new content when we write the file second time

Hi I am writing some data to a text file through java code but when i again run the code its again appending to the older data ,i want the new data to overwrite the older version.
can any one help..
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt" , true));
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.close();
code would help, but its likely you are telling it to append the data since the default is to overwrite. find something like:
file = new FileWriter("outfile.txt", true);
and change it to
file = new FileWriter("outfile.txt", false);
or just
file = new FileWriter("outfile.txt");
since the default is to overwrite, either should work.
based on your edit just change the true to false, or remove it, in the FileWriter. The 2nd parameter is not required and when true specifies that you want to append data to the file.
You mentioned a problem of incomplete writes... BufferedWriter() isn't required, if your file is smallish then you can use FileWriter() by itself and avoid any such issues. If you do use BufferedWriter() you need to .flush() it before you .close() it.
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt"));
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.flush();
out1.close();
Set append parameter to false
new FileWriter(yourFileLocation,false);
You can use simple File and FileWriter Class.
The Constructor of FileWrite Class provides 2 different varieties to make a file. One which only takes the Object of file. and another is with two parameters one with file object and second is boolean true/false which indicates whether file to be created is going to be append the contents or overwriting.
following code will do the overwriting of content.
public class WriteFile {
public static void main(String[] args) throws IOException {
File file= new File("new.txt");
FileWriter fw=new FileWriter(file,true);
try {
fw.write("This is first line");
fw.write("This is second line");
fw.write("This is third line");
fw.write("This is fourth line");
fw.write("This is fifth line");
fw.write("hello");
} catch (Exception e) {
} finally {
fw.flush();
fw.close();
}
}
}
It works same with PrintWriter class also, since it also provides 2 different varieties of Constructors same as FileWriter. But you can always refer to Java Doc API.

Categories