This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
I am trying to generate random numbers as ids, and save them in a file to easily access them. I am currently using BufferedWriter in order to write these to the file, but the problem is that I am not too sure about how to go about finding where I should start writing into the file. I am currently trying to use BufferedReader to figure out where the next line is to write, but I am not sure how I am supposed to save this offset or anything, or how a new line is represented.
void createIds(){
File writeId = new File("peopleIDs.txt");
try {
FileReader fr = new FileReader(writeId);
BufferedReader in = new BufferedReader(fr);
FileWriter fw = new FileWriter(writeId);
BufferedWriter out = new BufferedWriter(fw);
String line;
while((line = in.readLine()) != null){
//How do I save where the last line of null is?
continue;
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
If you simply want to add IDs to the end of the file, use the following FileWriter constructor:
FileWriter fw = new FileWriter(writeId, true);
This opens the FileWriter in append mode, allowing you to write output to a pre-existing file.
If you would like to write the IDs to a particular location within an existing file rather than just to the end, I am not sure if this is possible without first parsing the file's contents.
For more information, see the JavaDoc for FileWriter.
We need more information about the file itself: what are you searching for with BufferedReader?
If the file is empty/newly created then you don't need BufferedReader at all. Just create the PrintWriter and save your numbers.
I'm just guessing here, but I think the real problem is that you're not sure how to generate random numbers (since this doesn't appear in your example code).
Here's some example code that'll write random numbers into a text file:
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Example
{
public static void main(String[] args)
{
Random r;
PrintWriter writer;
r = new Random();
try
{
writer = new PrintWriter(new BufferedWriter(new FileWriter("Examplefile.txt")));
for (int i = 0; i < 10; i++)
writer.println(Integer.toString(r.nextInt(10)));
writer.close();
}
catch (IOException e)
{
}
}
}
You can do
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File("abc.txt"),true)));
writer.append("test");
} catch (IOException e) {
e.printStackTrace();
}
Related
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class TextFile {
private static void doReadWriteTextFile() {
try {
// input/output file names
String inputFileName = "README_InputFile.rtf";
// Create FileReader Object
FileReader inputFileReader = new FileReader(inputFileName);
// Create Buffered/PrintWriter Objects
BufferedReader inputStream = new BufferedReader(inputFileReader);
while ((inLine = inputStream.readLine()) != null) {
System.out.println(inLine);
}
inputStream.close();
} catch (IOException e) {
System.out.println("IOException:");
e.printStackTrace();
}
}
public static void main(String[] args) {
doReadTextFile();
}
}
I'm just learning Java, so take it easy on me. My program's objective is to read a text file and output it into another text file in reverse order. The problem is the professor taught us to to deal with strings and reverse it and such, but nothing about importing/exporting files. Instead, he gave us the following sample code which should import a file. The file returns 3 errors: The first two deal with inLine not being a symbol on lines 24 and 25. The last cannot find the symbol doReadTextFile on line 40.
I have no idea how to read this file and make the necessary changes to reverse and output into a new file. Any help is hugely appreciated.
I also had to change the file type from .txt to .rtf. I'm not sure if that affects how I need to go about this.
EDIT I defined inLine and fixed the doReadWritetextFile naming error, which fixed all my compiling errors. Any help on outputting into new file still appreciated!
I'm also aware he gave me bad sample code. It's supposed to be so we can learn troubleshooting, but with no working code to go off of and very extremely knowledge of the language, it's very difficult to see what's wrong. Thanks for the help!
The good practice will be to use a BufferedFileReader
BufferedFileReader bf = new BufferedFileReader(new FileReader(new File("your_file.your_extention")));
Then you can read lines in your file :
// Initilisation of the inLine variable...
String inLine = null;
while((inLine = bf.readLine()) != null){
System.out.println(inLine);
}
To output a file, you can use StringBuilder to hold the file contents:
private static void doReadWriteTextFile()
{
....
StringBuilder sb = new StringBuilder();
while ((inLine = inputStream.readLine()) != null)
{
sb.append(inline);
}
FileWriter writer = new FileWriter(new File("C:\\temp\\test.txt"));
BufferedWriter bw = new BufferedWriter(writer);
w.write(sb.toString());
bw.close();
}
This question already has answers here:
Write to text file without overwriting in Java
(9 answers)
Closed 8 years ago.
Hi there I'm trying to write strings to a textfile but there is a little problem. I completed my code with the help of the other questions at this site but when i try to add strings to a text file it erases everything in that text file and writes the input. But I want it to go to the nextline and write it. I couldn't solve it. I would appreciate any help. Thank you..
public static void addCar() throws IOException{
String string = transferBrand;
String string2 = ":"+transferModel;
System.out.println(string+string2);
File file = new File("HatchBack.txt");
try {
StringReader stringReader = new StringReader(string+string2);
BufferedReader bufferedReader = new BufferedReader(stringReader);
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(String line = bufferedReader.readLine(); line != null; line =bufferedReader.readLine()) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
(untested) Did you try this as mentioned in JavaDoc?
FileWriter fileWriter = new FileWriter(file, true);
I am new to Java and have been trying to string some open source code together to search tweets and finally was able to succeed. Then I wanted to save the output to a text file. I searched and reviewed console out methods, filewriter, printwriter and I found one on here that works but it's saving only one tweet and overwrites the previous one it saves. How can I properly append the existing text file without overwriting a previous save and make sure it saves all the tweets from the console screen? Example code below:
JSONObject js = new JSONObject(buff.toString());
JSONArray tweets = js.getJSONArray("results");
JSONObject tweet;
for(int i=0;i<tweets.length();i++) {
tweet = tweets.getJSONObject(i);
PrintWriter out;
try {
out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt"));
System.out.println((i+1)+")http://twitter.com/"+tweet.getString("from_user")+" at "+tweet.getString("created_at"));
System.out.println(tweets.getJSONObject(i).getString("text")+"\n");
out.println((i+1)+")http://twitter.com/"+tweet.getString("from_user")+" at "+tweet.getString("created_at"));
out.println(tweets.getJSONObject(i).getString("text")+"\n");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You are so tantalizingly close. You just need to open the FileWriter with append set to true. Append will make it add to the end of the file, as opposed to overwriting it every time.
out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt", true));
Change this line (Because it will erase your previously written data):
out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt"));
For (Here you are setting Append mode to true)
out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt"), true);
Default mode is set to false so it will overwrite your file.
Instead of creating object of PrintWriter and FileWriter object during each iteration of your for loop you should initialize PrintWriter outside of you for loop(its will improve performance)finally to release resource.
PrintWriter out = null ;
try
{
// putting
out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt"),true); // appending file if exists.
// JSON Parsing instructions
for(int i=0;i<tweets.length();i++)
{
// processing logic and write operation to file
}
}
catch(CustomExceptions e) {//All other exception handling}
catch(Exception e){//Generic exception handling }
finally{
if(out != null
{
out.close();
}
}
public final String path ="your path"
PrintWriter pw = new PrintWriter(new FileWriter(path),true);/*automatically append the line you want to save and if false it will overwrite the data */
pw.write("what ever you want")
pw.close();
I want to read a huge csv file. We are using superCSV to parse through the files in general. In this particular scenario, the file is huge and there is always this problem of running out of memory for obvious reasons.
The initial idea is to read the file as chunks, but I am not sure if this would work with superCSV because when I chunk the file, only the first chunk has the header values and will be loaded into the CSV bean, while the other chunks do not have header values and I feel that it might throw an exception. So
a) I was wondering if my thought process is right
b) Are there any other ways to approach this problem.
So my main question is
Does superCSV have the capability to handle large csv files and I see that superCSV reads the document through the BufferedReader. But I dont know what is the size of the buffer and can we change it as per our requirement ?
#Gilbert Le BlancI have tried splitting into smaller chunks as per your suggestion but it is taking a long time to break down the huge file into smaller chunks. Here is the code that I have written to do it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
public class TestFileSplit {
public static void main(String[] args) {
LineNumberReader lnr = null;
try {
//RandomAccessFile input = new RandomAccessFile("", "r");
File file = new File("C:\\Blah\\largetextfile.txt");
lnr = new LineNumberReader(new FileReader(file), 1024);
String line = "";
String header = null;
int noOfLines = 100000;
int i = 1;
boolean chunkedFiles = new File("C:\\Blah\\chunks").mkdir();
if(chunkedFiles){
while((line = lnr.readLine()) != null) {
if(lnr.getLineNumber() == 1) {
header = line;
continue;
}
else {
// a new chunk file is created for every 100000 records
if((lnr.getLineNumber()%noOfLines)==0){
i = i+1;
}
File chunkedFile = new File("C:\\Blah\\chunks\\" + file.getName().substring(0,file.getName().indexOf(".")) + "_" + i + ".txt");
// if the file does not exist create it and add the header as the first row
if (!chunkedFile.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(chunkedFile.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(header);
bw.newLine();
bw.close();
fw.close();
}
FileWriter fw = new FileWriter(chunkedFile.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);
bw.newLine();
bw.close();
fw.close();
}
}
}
lnr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
You can define header in the parser java class itself. That way you don't need a header row in CSV files.
// only map the first 3 columns - setting header elements to null means those columns are ignored
final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, null, null };
beanReader.read(CustomerBean.class, header)
or
You can also use dozer extension of SuperCSV api.
I'm not sure what the question is. Reading a line at a time as a bean takes roughly constant memory consumption. If you store all read objects at once then Yes you run out of memory. But how is this super csv's fault ?
I wrote the below part of the code but I couldn't bind the arraylist with search and replace
so my csv file is as like below
1/1/1;7/6/1
1/1/2;7/7/1
I want to search the file 1.cfg for 1/1/1 and change it to 7/6/1 and 1/1/2 change to 7/7/1 and it goes so on.
Thank you all in advance
It's now only printing in a new file only the last line of the old File
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ChangeConfiguration {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream degistirilecek = new FileInputStream("c:/Config_Changer.csv");
FileInputStream config = new FileInputStream("c:/1.cfg");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(config);
DataInputStream degistir = new DataInputStream(degistirilecek);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedReader brdegis = new BufferedReader(new InputStreamReader(degistir));
List<Object> arrayLines = new ArrayList<Object>();
Object contents;
while ((contents = brdegis.readLine()) != null)
{
arrayLines.add(contents);
}
System.out.println(arrayLines + "\n");
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Couldn't modify this part error is here :(
BufferedWriter out = new BufferedWriter(new FileWriter("c:/1_new.cfg"));
out.write(strLine);
out.close();
}
in.close();
degistir.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
You are opening the file for reading when you declare:
BufferedReader br = new BufferedReader(new InputStreamReader(in));
If you know the entire file will fit in memory, I recommend doing the following :
Open the file and read it's contents in memory into a giant string, then close the file.
Apply your replace in one shot to the giant string.
Open the file and write (e.g use a BufferedWriter) out the contents of the giant string, then close the file.
As a side note, your code as posted will not compile. The quality of the responses you receive are correlated with the quality of the question asked. Always include an SCCE with your question to increase the chance of getting a precise answer to your question.
can you elaborate the purpose of the program?
if it is a simple content replacement in a file.
then just read a line and store it in a string. then use string replace method for replacing a text in a string.
eg:
newStrog=oldString.replace(oldVlue,newValue);