Java - Copy long text of a text file to another - java

I have one txt file with a very, very long text and I want to read, make some changes and copy that text to other txt files. The problem is that I can't read the file by the BufferedReader because I'd have to store the text in a variable, but that can't be done due to capacity and then write it to another file... Is there a way this can be done?

BuffereReader(Writer) works fine for this tasks (reading,writing large files)
BufferedWriter bw=null ;
BufferedReader br=null;
try{
br = new BufferedReader(new FileReader(new File("e:/temp/1.txt")));
bw = new BufferedWriter(new FileWriter(new File("e:/temp/2.txt")));
String st="";
while((st=br.readLine())!=null){
bw.write(st.replace("a","b"));
bw.newLine();
}
bw.close();
br.close();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
}

Related

Appending a string on the specific place in txt file - Java

I'am trying to append string(link) to the txt file on the specific place(In line where is "Link:"), to get line in file like "Link: www.link.something". I am using next code but my logic doesn't work.
if(file.getName().equals(filename+".txt")) {
link = line;
BufferedReader br;
BufferedWriter bw;
boolean no=false;
String lineE;
String data="Link:";
String lessonPath=link;
br = new BufferedReader(new FileReader(file));
while((lineE =br.readLine()) !=null){
if(!no){
data=line;
no=true;
}else{
data = data+"\n"+lineE;
}
}
bw = new BufferedWriter(new FileWriter(file));
bw.write(data+"\n"+lessonPath);
System.out.println(data+lessonPath);
bw.flush();
bw.close();
br.close();
}
If you can modify the text file then you could use StringSubstitutor to replace the template.

Java program is not writing all the records to the output file using the BufferedWriter

This below code is not able to write more than 29499 lines in the output file. More over the last line was printed only half. I have verified there is no issue with the program as the program is print all the 25000 lines in console.
FileReader fr = new FileReader(System.getProperty("user.dir") + "/json/Sample.json");
FileWriter fw = new FileWriter(System.getProperty("user.dir") + "/json/output.json");
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
String line=br.readLine();
if (line == null)
{
br.close();
fr.close();
bw.flush();
bw.close();
fw.close();
}
while (line!=null) {
Gson gson = new Gson();
bw.write(record+"\n");
line=br.readLine();
}
You only close and flush your readers & writers if the first line is null. You presumably instead want to do this after your loop completes, which will ensure that (exceptions aside) they'll always close.
Even better, use the try with resources statement to avoid having to close / flush them manually at all - this will also handle the case where an exception it thrown.

Unable to rename and delete file in Java

I am doing a project in Java using NetBeans and I need to modify a file. So I overwrite the whole file in another temporary file, but at the end I could not rename the temporary file or delete the main file. Any solutions?
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");
FileReader fr = new FileReader("F:\\nb\\project_inventory\\Employee_info.txt");
BufferedReader br =new BufferedReader(fr);
FileWriter fw = new FileWriter(tf);
PrintWriter bw =new PrintWriter(fw);
String line;
while((line=br.readLine())!=null)
{
if(line.contains(del_id)) continue;
bw.println(line);
}
bw.close();
fw.close();
br.close();
fr.close();
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
tf.renameTo(real);
I just tried 5 of the above project lines as below and got the desired result,
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");
try{
tf.createNewFile(); // for creating the new file
}
catch(IOException e){
e.printstacktrace();
}
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
tf.renameTo(real);
Employee_info.txt is getting deleted as well as temp.tmp is getting renamed as Employee_info.txt too.
Also, it is always recommended to put the code for delete/rename inside try/catch block like below:
try{
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
}
catch(IOException e){
e.printstacktrace();
}
Please provide the error message, to help you further.

Editing file in External Storage

In my app, I am writing a file and storing it in external storage
But everytime I want to edit it, I have to get the data of file, delete it and then recreate it using the new data.
But is there any way to directly edit a existing file instead of deleteing and recreating it?
Thanks to blackbelt for helping me out.
Here is how to do this -
File gpxfile = new File(File address, "filename.txt");
BufferedWriter bW;
try {
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write("file text");
bW.newLine();
bW.flush();
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
This will rewrite the file. If you just want to add a line instead of replacing the whole thing, then replace
bW = new BufferedWriter(new FileWriter(gpxfile));
with
bW = new BufferedWriter(new FileWriter(gpxfile, true));

Saving String Input on Android

Right, I've been trying to find a solution to this for a good while, but it's just not working for some reason.
In short, what I want to do is save every input String the user inputs into a file. Every time the activity is created again, I want to re-input these strings into a new instance of an object.
This code is what I use to create the file and read info from it, used in the onCreate() method of activity
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
String s; // This feeds the object MegaAndroid with the strings, sequentially
while ((s = in.readLine()) != null) {
MegaAndroid.add(s);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
After that, every time the user inputs some text, the strings are saved onto the file:
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(message); // message is a string that holds the user input
out.close();
} catch (IOException e) {
e.printStackTrace();
}
For some reason, however, every time the application is killed, the data is lost.
What am I doing wrong?
EDIT: Also, if I were to access this file from another class, how can I?
As we discussed in the commend section the chief problem with the code is that your execution of FileWriter occurred prior to your FileReader operation while truncating the file. For you to maintain the file contents you want to set the write operation to an append:
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(message);
out.newLine();
out.close();
However, if every entry on the EditText is received then shipped into the file you'll just be writing data byte after byte beside it. It is easy to get contents similar to
This is line #1This is line #2
Instead of the desired
This is line #1
This is line #2
which would be corrected by having the BufferedWriter pass a newline after each write to the file.
This is what I do for file reading.
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
Log.d(TAG,"path: "+dir.getAbsolutePath());
File file = new File(dir, "VERSION_FILENAME");
FileInputStream f = new FileInputStream(file);
//FileInputStream fis = context.openFileInput(VERSION_FILENAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
Log.d(TAG,"first line versions: "+line);
while(line != null){
Log.d(TAG,"line: "+line);
//Process line how you need
line = reader.readLine();
}
reader.close();
f.close();
}
catch(Exception e){
Log.e(TAG,"Error retrieving cached data.");
}
And the following for writing
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
File file = new File(dir, "CONTENT_FILENAME");
FileOutputStream f = new FileOutputStream(file);
//FileOutputStream fos = context.openFileOutput(CONTENT_FILENAME, Context.MODE_PRIVATE);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));
Set<String> keys = Content.keySet();
for(String key : keys){
String data = Content.get(key);
Log.d(TAG,"Writing: "+key+","+data);
writer.write(data);
writer.newLine();
}
writer.close();
f.close();
}
catch(Exception e){
e.printStackTrace();
Log.e(TAG,"Error writing cached data.");
}
You can use the private mode if you don't want the rest of the world to be able to see your files, but it is often useful to see them when debugging.

Categories