Java File - Open a File and Write to It

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}

catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}

finally {
if(out != null) {
out.close();
}
}

How do I create a file and write to it?

Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.

Note that each of the code samples below will overwrite the file if it already exists

Creating a text file:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creating a binary file:

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+ users can use the Files class to write to files:

Creating a text file:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Creating a binary file:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);

How to append text to an existing file in Java?

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

Java 7+

For a one-time task, the Files class makes this easy:

try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}

Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:

private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}

However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:

try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}

Notes:

  • The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
  • Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.


Older Java

try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}


Exception Handling

If you need robust exception handling for older Java, it gets very verbose:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}

How to open and read a file and write specific content to a new file?

Looks like this is your programming homework, so I won't give you the exact coding. Unless your input file is empty, otherwise your readLines() method will loop forever. if it is not a must, you don't need to count the no. of lines before reading each of them. Here is what you can do:

read one line from the file
while the line is not null
check if the line begins with one of the three identifier you want
if so, append the line to a string
if not, do nothing
if the accumulated string has all three required line, use `ReadLatLong` to do an output
(simplest way is to use 3 bool flags)
read another line using the same variable name as at the beginning
end while

Hope this helps.

EDIT: OK, since RoverMAX has given his coding, I give you another version for you to consider.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestCampusImages {

static final String file_path1 = "CampusImages.txt";
static final String file_path2 = "CampusImageIDs.txt";
static final Pattern pID = Pattern.compile("(?<=IDENTIFIER:)[\\d\\s]*");
static final Pattern pLAT = Pattern.compile("(?<=LATITUDE:)[\\d\\s-.]*");
static final Pattern pLONG = Pattern.compile("(?<=LONGITUDE:)[\\d\\s-.]*");

public static void main(String[] args) {
int id = 0;
float latitude = 0.0f, longitude = 0.0f;
try {
File inFile = new File(file_path1);
BufferedReader textReader = new BufferedReader(new FileReader(inFile));
File outFile = new File(file_path2);
PrintWriter out = new PrintWriter(outFile);
String inLine = textReader.readLine();
while (inLine != null) {
Matcher m = pID.matcher(inLine);
if (m.find()) {
id = Integer.parseInt(m.group().trim());
}
m = pLAT.matcher(inLine);
if (m.find()) {
latitude = Float.parseFloat(m.group().trim());
}
m = pLONG.matcher(inLine);
if (m.find()) {
longitude = Float.parseFloat(m.group().trim());
}
if ((id!=0) && (latitude!=0.0f) && (longitude!=0.0f)) {
out.println(String.format("%d | %f | %f ", id, latitude, longitude));
id = 0;
latitude = 0.0f; longitude = 0.0f;
}//end if
inLine = textReader.readLine();
}//end while
textReader.close();
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}//end try
} //end main

} //end TestCampusImages

This code is good since it allow you to further process the data extract if so required. But it has no validation on the input file. So be careful. If you consider any of the response here is helpful, please mark it as an answer.

Can PrintWriter write to an open text file (Java)

Setting append to true in the FileWriter:

append - boolean if true, then data will be written to the end of the file rather than the beginning.

If you've got 50 machines doing this all at the same time, there's going to be conflicts. Your computer complains when you try to modify a file that's being used by another process, don't go throwing in 50 more contenders.

You could try using Sockets.

Whichever machine holds that file, designate that as the 'server' and make the other machines 'clients'. Your clients send messages to the server, your server appends those messages to the file in a synchronised manner.

You could then prevent your ~50 clients from directly changing the logs file with some network & server security.

Java - is there a way to open a text file if it does not exist already, and append to it if it does exist?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class AreaOfCircle {
private static double PI = Math.PI;
private double radius;
private static double area;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
AreaOfCircle a = new AreaOfCircle();
System.out.print("Type in the radius of circle: ");
a.radius = keyboard.nextDouble();
getArea(a.radius);
System.out.print("Name of the txt file you want to create:");
String fileName = keyboard.next();
keyboard.nextLine();
try {
File myFile = new File(fileName);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter fw = new FileWriter(myFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("The area of the circle is " + area + ".\n");
bw.close();
}
catch (IOException e) {
System.out.println("IOException Occured");
e.printStackTrace();
}
}

public static void getArea(double n) {
area = n * PI;
}
}

The only change I made is
String fileName = keyboard.next(); from //keyboard.nextLine()
The above code worked for me . Hope this helps.

Opening an existing file in Java and closing it.

The answers that advise against closing and re-opening the file each time are quite correct.

However, if you absolutely have to do this (and it's not clear to me that you do), then you can create a new FileWriter each time. Pass true as the second argument when you construct a FileWriter, to get one that appends to the file instead of replacing it. Like

FileWriter writer1 = new FileWriter(filename, true); 


Related Topics



Leave a reply



Submit