i was wondering if there was a way to add to text files already created. because when i do this on an already created file:
public Formatter f = new Formatter("filename.txt");
it re-writes the current filename.txt with a blank one.
thanks, Quinn
Yes, use the constructor with an OutputStream argument instead of a File argument. That way you can open an OutputStream in append mode and do your formatting on that. Link
Try using the constructor for Formatter which takes an Appendable as an argument.
There are several classes which implement the Appendable interface. The most convenient, in your case, should be FileWriter.
This FileWrite constructor will let you open a file (whose name is specified as a String), in append mode.
Use FileOutputStream with append boolean value as true eg new FileOutputStream("C:/concat.txt", true));
Example
public class FileCOncatenation {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/concat.txt", true));
File file2 = new File("C:/Text/file2.rxt");
System.out.println("Processing " + file2.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(file2
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
// }
pw.close();
System.out.println("All files have been concatenated into concat.txt");
}
}
Related
I have a simple Properties exercise
1. Read the time of program run from a configuration document ProgramRunCounter.ini
2. Each time the program run, add one more time
3. Modify the information in document
Here is the code:
class ProgramRunCounter {
public static void counter() throws IOException{
Properties prop = new Properties();
File f = new File("ProgramRunCounter.ini");
BufferedReader br;
BufferedWriter bw;
String key = "times";
String value;
int counter;
if (!f.exists()) {
f.createNewFile();
System.out.println("File created");
}
//Problem is here
br = new BufferedReader(new FileReader(f));
prop.load(br);
value = prop.getProperty(key);
bw = new BufferedWriter(new FileWriter(f));
if (value != null) {
counter = Integer.parseInt(value);
System.out.println("This program has run " + counter + " times");
counter++;
value = String.valueOf(counter);
prop.setProperty(key, value);
prop.store(bw, "One more time run!");
} else {
prop.setProperty(key, "1");
prop.store(bw, "First time run!");
}
br.close();
bw.close();
}
}
public class PropertiesDemo {
public static void main(String[] args) {
try {
ProgramRunCounter.counter();
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
}
It works well, but problem is if i change the order of the codes like this, it can't work anymore
br = new BufferedReader(new FileReader(f));
bw = new BufferedWriter(new FileWriter(f));
prop.load(br);
value = prop.getProperty(key);
So why?
It doesn't allow insert bw = new BufferedWriter(new FileWriter(f)); between br = new BufferedReader(new FileReader(f)); and prop.load(br);?
What is the principle?
The devil is in the details. First let me just say, that you may want to just use the "new" (not soo new anymore) IO file API (i.e. Files.newBufferedReader / Files.newBufferedWriter(f.toPath()), ...). Not a must, but it makes things easier.
If you look at the javadoc of newBufferedWriter you see the following:
Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.
That efficiency is probably the reason why you do not see any content anymore while you are reading the file (here I assume the same efficiency is also applied under the hood, if you just use your own instantation of BufferedWriter with FileWriter which uses a FileOutputStream with append=false. If you follow all the calls you end up in a native method, so unfortunately I can't say for sure).
Now if you use Files.newBufferedWriter and you just alter the OpenOption to say SYNC or something other then TRUNCATE_EXISTING, the reader is able to load the properties again regardless of which initialization comes first, e.g.
br = Files.newBufferedReader(f.toPath());
bw = Files.newBufferedWriter(f.toPath(), StandardOpenOption.SYNC);
First off I am new at coding in java. I have done extensive research prior to posting this question but have not found the exact answer to my question. I am sure it is my lack of experience, but any assistance the community can provide would be much appreciated.
I am trying to debug a utility class that I have coded. The code is working except for the bit about adding a new line to the substituted text.
Here is the piece of code that is generating an error in NetBeans IDE. The error is incompatible types: Boolean can't be converted to int
try (BufferedWriter bw = new BufferedWriter(new FileWriter (NewCSVFile),true))
What I am trying to do is get this code to read a CSV text file, substitute and the write the new csv data to a new file but preserve the original new lines in the file. And, I want to ensure that the method used is platform independent thus why I am using BufferedWriter.
Here is all the code for your review.
public class TxtFileConverter {
public static void main (String[] args) {
// Location of the file you want to work with.
File CSVFile = new File("/Users/data.csv");
File NewCSVFile = new File("/Users/NewData.csv");
String search = "[,](?!\\w)";
String replace = ",0";
try{
FileReader fr = new FileReader(CSVFile);
String s;
String totalStr = "";
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
totalStr += s;
}
totalStr = totalStr.replaceAll(search, replace);
try (BufferedWriter bw = new BufferedWriter(new FileWriter
(NewCSVFile),true)) {
bw.write(totalStr);
bw.newLine();
}
}
}catch(IOException e){
}
}
}
I think you are trying to read some lines from a file and write it to another file. In the output file, you get all the code in a single line.
I think the bug is in this piece of code.
while ((s = br.readLine()) != null) {
totalStr += s;
}
If you add a statement to add a new line character after reading a line from input file, you should get the desired output.
while ((s = br.readLine()) != null) {
totalStr += s;
totalStr += "\n";
}
The following code adds a newline character at the end of the file.
bw.newLine();
What do you think that true argument is doing in the BufferedWriter constructor? The second and optional argument is the buffer size, an integer. You probably don't even need to supply that argument unless you're doing something rather odd.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(NewCSVFile)))
BufferedWriter has only two constructors:
public BufferedWriter(Writer out) //sz = defaultCharBufferSize = 8192
public BufferedWriter(Writer out, int sz) //sz Output-buffer size, a positive integer
There is no option with second boolean argument. I recommend to use first constructor in your case.
I have a text file with some text in it and i'm planning on replacing certain characters in the text file. So for this i have to read the file using a buffered reader which wraps a file reader.
File file = new File("new.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
But since i have to edit characters i have to introduce a file writer and add the code which has a string method called replace all. so the overall code will look as given below.
File file = new File("new.txt");
FileWriter fw = new FileWriter(file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
fw.write(br.readLine().replaceAll("t", "1") + "\n");
}
Problem is when i introduce a file writer to the code (By just having the initialization part and when i run the program it deletes the content in the file regardless of adding the following line)
fw.write(br.readLine().replaceAll("t", "1") + "\n");
Why is this occurring? am i following the correct approach to edit characters in a text file?
Or is there any other way of doing this?
Thank you.
public FileWriter(String fileName,
boolean append)
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the
file rather than the beginning.
To append data use
new FileWriter(file, true);
The problem is that you're trying to write to the file while you're reading from it. A better solution would be to create a second file, put the transformed data into it, then replace the first file with it when you're done. Or if you don't want to do that, read all of the data out of the file first, then open it for writing and write the transformed data.
Also, have you considered using a text-processing language solution such as awk, sed or perl: https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files
You need to read the file first, and then, only after you read the entire file, you can write to it.
Or you open a different file for writing and then afterwards you replace the old file with the new one.
The reason is that once you start writing to a file, it is truncated (the data that was in the file is deleted).
The only way to avoid that is to open the file in "append" mode. With that mode, you start writing at the end of the file, so you don't delete its content. However, you won't be able to modify the existing content, you will only add content.
Maybe like this
public static void main(String[] args) throws IOException {
try {
File file = new File("/Users/alexanderkrum/IdeaProjects/printerTest/src/atmDep.txt");
Scanner myReader = new Scanner(file);
ArrayList<Integer> numbers = new ArrayList<>();
while (myReader.hasNextLine()) {
numbers.add(myReader.nextInt() + 1);
}
myReader.close();
FileWriter myWriter = new FileWriter(file);
for (Integer number :
numbers) {
myWriter.write(number.toString() + '\n');
}
myWriter.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Just add at last :
fw.close();
this will close it ,then it will not delete anything in the file.
:)
I am using java File Streams. I have two files. First file may or may not be empty. The second file contains strings and floats. If the first file is empty then I want to copy second file in it. else I want to merge the files.
Have tried RandomAccessFile but it's not working.
If you want to copy a file then use
public static Path copy(Path source,
Path target,
CopyOption... options)
throws IOException
File.copy()
If you want to merge them then open the file in write mode in which you want to append the data with appending mode.
BufferedWriter bw = new BufferedWritr(new FileWriter("file.txr",true));
and then write the data in bw which you have read from the source file.
My solution would look like this:
public void CopyFile(File one, File two) throws IOException {
// Declare the reader and the writer
BufferedReader in = new BufferedReader(new FileReader(one));
BufferedWriter out;
String contentOfFileOne = "";
// Read the content of the first file
while(in.ready()){
contentOfFileOne += in.readLine();
}
// Trim all whitespaces
contentOfFileOne.trim();
// If the first file is empty
if(contentOfFileOne.isEmpty()){
// Create a new Writer to the first file and a reader
// from the second file
in.close();
out = new BufferedWriter(new FileWriter(one));
in = new BufferedReader(new FileReader(two));
while(in.ready()){
String currentLine = in.readLine();
out.write(currentLine);
}
// Close them accordingly
in.close();
out.close();
} else {
// If the first file contains something
in.close();
out = new BufferedWriter(new FileWriter(one,true));
in = new BufferedReader(new FileReader(two));
// Copy the content of file two at the end of file one
while(in.ready()){
String currentLine = in.readLine();
out.write(currentLine);
}
in.close();
out.close();
}
}
The comments should explain the functionality.
I think this is supposed to be the most efficient option
FileChannel f1 = FileChannel.open(Paths.get("1"), StandardOpenOption.APPEND);
FileChannel f2 = FileChannel.open(Paths.get("2"));
f1.transferFrom(f2, f1.size(), Long.MAX_VALUE);
So I'm learning new things day by day in Java, and I hope one day I should have same knowledge in Java as in PHP.
I'm trying to make a class that is similar to fopen, fwrite, fclose in PHP like:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
I also need the method of writing
o - for delete and write/overwrite
a - for append at end
and a read function that returns the the content line by line, so I can put it into an array , like file_get_contents(file);
This is what I have so far ...
import java.io.*;
import java.util.Scanner;
/**
Read and write a file using an explicit encoding.
Removing the encoding from this code will simply cause the
system's default encoding to be used instead.
**/
public final class readwrite_txt
{
/** Requires two arguments - the file name, and the encoding to use. **/
public static void main(String[] args) throws IOException
{
String fileName = "text.txt";
String encoding = "UTF-8";
readwrite_txt test = new readwrite_txt(fileName,encoding);
test.write("argument.txt","some text","UTF-8","o");
}
/** Constructor. **/
readwrite_txt(String fileName, String encoding)
{
String fEncoding = "text.txt";
String fFileName = "UTF-8";
}
/** Write fixed content to the given file. **/
public void write(String fileName,String input,String encoding,String writeMethod) throws IOException
{
// Method overwrite
if(writeMethod == "o")
{
log("Writing to file named " + fileName + ". Encoding: " + encoding);
Writer out = new OutputStreamWriter(new FileOutputStream(fileName), encoding);
try
{
out.write(input);
}
finally
{
out.close();
}
}
}
/** Read the contents of the given file. **/
public void read(String fileName,String output,String encoding,String outputMethod) throws IOException
{
log("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(fileName), encoding);
try
{
while (scanner.hasNextLine())
{
text.append(scanner.nextLine() + NL);
}
}
finally
{
scanner.close();
}
log("Text read in: " + text);
}
// Why write System.out... when you can make a function like log("message"); simple!
private void log(String aMessage)
{
System.out.println(aMessage);
}
}
also, I don't understand why I must have
readwrite_txt test = new readwrite_txt(fileName,encoding);
instead of
readwrite_txt test = new readwrite_txt();
I just want to have an simple function similar to that in PHP.
EDITED
So my function must be
$fp = fopen('data.txt', 'w'); ==> readwrite_txt test = new readwrite_txt(filename,encoding,writeMethod);
fwrite($fp, '23'); ==> test.write("the text");
fclose($fp); ==> ???
to read a file in java you can
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) //Start of reading file
{
//what you want to do with every line is here
}
but for readwrite_txt test = new readwrite_txt(); problem ..
you must have another constructor inside the class that doesn't take any parameters
Have a look at the following file handling tutorials (Google is littered with them):
http://www.javapractices.com/topic/TopicAction.do?Id=42
http://www.coderanch.com/t/403914/java/java/do-read-entire-file-all
Pay attention to the following classes:
FileInputStream
FileOutpuStream
Scanner
There's all sorts of examples out there for you to learn from.
You can use the BufferedReader, here is an example and BufferedWriter, here is an example of write and here is an example for appending. For reading line-by-line you can use the readLine method of BufferedReader. You don't need those parameters in your constructor, because you don't use them, but you don't even need a class to implement these features because there are already standard classes for this purpose.
I hope this helps.