This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 6 years ago.
private void AddAccount(String usernamenew, String passwordnew) {
final String FileName = "F:/TextFiles/loginaccs.txt";
File file = new File(FileName);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(usernamenew);
bw.newLine();
bw.write(passwordnew);
bw.newLine();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, I tried to write two extra lines to a text file, which is a new username and a new password.
After deleting some of the lines, the program deletes everything in the text file and write two lines, which is not what I wanted.
Am I doing something wrong? Thanks in Advance.
After you write to the BufferedWriter, for the file, you then close it, which is fine.
However, you then create another FileOutputStream. In addition, you should not have a reader and writer of the same file at the same time. All you need to do is create the BufferedWriter, write the file and close it.
private void AddAccount(String usernamenew, String passwordnew) {
final String FileName = "F:/TextFiles/loginaccs.txt";
File file = new File(FileName);
try {
// BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(usernamenew);
bw.newLine();
bw.write(passwordnew);
bw.newLine();
bw.close();
// FileOutputStream fos = new FileOutputStream(file);
// fos.close();
// br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
public class Client {
private Scanner scanner;
private String fileClient="client.txt";
public File client =new File(fileClient);
public void deletClient() {
int lineRemove =GetLineRemove();
String tempFile="temp.txt";
File newfile=new File(tempFile);
int line=0;
String currentLine;
try {
FileWriter fw=new FileWriter(tempFile,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
FileReader fr=new FileReader(fileClient);
BufferedReader br=new BufferedReader(fr);
while((currentLine=br.readLine())!=null ) {
line++;
if(line !=lineRemove) {
pw.println(currentLine);
}
}
pw.flush();
fr.close();
bw.close();
pw.close();
br.close();
fw.close();
// i try to delet a file
client.delete();
// create a file have the same name
File dumy=new File(fileClient);
// rename it to first file
newfile.renameTo(dumy);
}catch(Exception e){
System.out.print(e);
}
}
I want to remove a line from a file but when i do that i found the first file still exist and the second file what should get rename to the first file still have has it name temp i don't know should do so i hope u can help me to know where is the problem.
I am using below code to write data in a file.
public static void writeDataToFile(final String fileName, final String fileContents) {
try {
File file = new File(Environment.getExternalStorageDirectory() + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(fileContents);
writer.flush();
writer.close();
} catch (IOException e) {
LogUtility.logInfo(TAG, e.getMessage());
}
}
Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help
You can set the append flag to false in the FileWriter constructor. Then, use the write() function instead of the append() function
FileWriter writer = new FileWriter(file, false);
writer.write(fileContents);
Why don't you remove the file if it exists:
if (!file.exists()) {
file.createNewFile();
} else {
file.delete()
file.createNewFile();
}
If file does not exist, you have written code to create a new file.
Likewise, if file exists, you can delete the file, and create new one
Before deleting old file, you can copy contents into a String, and add them to content that is to be written in file before writing into file.
StringBuilder contentToWrite = new StringBuilder();
contentToWrite.append(newContent);
if (!file.exists()) {
file.createNewFile();
} else {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line).append("\n");
line = bufferedReader.readLine();
}
contentToWrite.append("\n\n" + sb);
file.delete();
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(contentToWrite);
writer.flush();
writer.close();
PS: Don't forget to close FileReader and BufferedReader in a finally statement.
Hello I am new to Android development. I am developing an app as a training. So now my target is to add some new text to an existing text file.
For example: I have a text file in "sdCard/android.txt" and in this file there are some data written "I love android". Now I want to add some more texts "It is awesome" in a new line of that file.
Finally the android.txt ahould look like this:
I love android
It is awesome
So how can I achieve that?
You can just do it as you do it in Java.
try {
String fn = getExternalFilesDir(null) + File.separator + "android.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(fn, true));
bw.write("\nIt is awesome\n");
bw.close();
// checking
BufferedReader br = new BufferedReader(new FileReader(fn));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
You can look at this example and use a BufferedWriter. When you execute File-Read or -Write operations, make sure to always use try/catch blocks.
public void appendText () {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Path-to-your-file", true));
bw.write("text-to-append");
bw.newLine();
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
You should definitely read about IO (Input-Output) Operations in Android/Java. https://docs.oracle.com/javase/tutorial/essential/io/
Good luck!
I want add few strings to a text file in a particular location.
I have used BufferedReader to read the text file. Then I added the string at the particular position and wrote the modified text to a new temp file using BufferedWriter.
Then I deleted the old file and renamed the temp file to old file name.
This works sometimes and does not work sometimes. The delete() function sometimes does not delete the file. I have closed all the BufferedWriter's, but the problem still occurs sometimes.
Code:
public boolean cart(String uname, String item) throws IOException {
File file = new File("C:\\$$$$.tmp");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
File fileop = new File("C:\\value.text");
FileReader fr = new FileReader(fileop.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
String val[] = line.split(",");
if (val[0].equals(uname)) {
String linenew = line + item + "&";
bw.append(linenew);
bw.newLine();
bw.flush();
} else {
bw.append(line);
bw.newLine();
bw.flush();
}
}
br.close();
bw.close();
fileop.delete();
file.renameTo(fileop);
return true;
}
I found the answer by myself after spending one full day of searching..
Answer is:
It is enough to close the bufferedReader but also the fileReader..
fr.close(); should be inserted after br.close();
In the first step am creating a file say test1.txt and adding records to it, and the rest records to test2.txt. Now i want to append the records of test2.txt to test1.txt. How to append them to test1.txt. The reason am dividing the files is i have a List with about 53K records, which am unable to write in a single file, as the buffer writer is closing as its reaching 52K.
The function am using for creating a single file is
public void exportApprovedList() throws IOException {
File approvedWhiteListFile = new File("/var/tmp/livecron/dictionary.common");
BufferedWriter bw = new BufferedWriter(new FileWriter(approvedWhiteListFile));
if (approvedWhiteListFile.exists()) {
List<WhiteListTerm> approvedWhiteList = whiteListBO.getByStatus("APPROVED");
for (WhiteListTerm whiteList : approvedWhiteList) {
bw.write(whiteList.getTerm() + "|" +
whiteListCategoryBO.getById(whiteList.getCategoryId()).getCategoryname());
bw.newLine();
}
}
bw.close();
}
try this....
import java.io.*;
public class FileReadWrite {
public void writeFile(String sorcefile)
{
try{
FileInputStream fis = new FileInputStream(sorcefile);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
FileWriter fw=new FileWriter("src/output.java",true);
BufferedWriter bw=new BufferedWriter(fw);
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
System.out.println (strLine);
bw.append(strLine);
}
//Close the input stream
br.close();
dis.close();
fis.close();
fw.flush();
bw.flush();
fw.close();
bw.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String args[])
{
FileReadWrite frw=new FileReadWrite();
frw.writeFile("sorce file name wit hfull path");
}
}