How to Write Text File Java

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);

What is the simplest way to write a text file in Java?

With Java 7 and up, a one liner using Files:

String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());

How to Write text file Java

I think your expectations and reality don't match (but when do they ever ;))

Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))

public class TestWriteFile {

public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);

// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());

writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}

Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:

writer = new BufferedWriter(new FileWriter(logFile, true));

How to write 1 to 1000 numbers into text file using java?

You can use PrintWriter and FileWriter to write into the file. You can refer below code for your reference:

public class FileWriterExample {
public static void main(String args[]) {
try {
PrintWriter fileout = new PrintWriter(new FileWriter("C://Users//Desktop//random.txt"));

for (int i = 1; i < 1001; i++) {
fileout.println(i);
}
fileout.close();
System.out.println("success...");
} catch (Exception e) {
System.out.println(e);
}
}
}

How to implement code for writing in a text file (Java)

I suggest using Customer methods and fields for operations concerning a particular customer, this will encapsulate behaviour common to all customers. You need to have the Customer class look like this:

public class Customer {
String cardID;
String name;
String address;

public Customer(String cardID, String name, String address) {
this.cardID = cardID;
this.name = name;
this.address = address;
}
}

Then you can create a method saveToFile inside this class:

public void saveToFile(String fileToWrite) {
List<String> lines = Arrays.asList(cardID, name, address);
Path file = Paths.get(fileToWrite);
try {
Files.write(file, lines);
} catch (IOException ex) {
System.err.println("Error writing to " + file);
}
}

(for other approaches to creating and writing to text files, see this question). After creating this method, use it in your main method:

// register customer                
Customer customer = new Customer(cardID, name, address);
customer.saveToFile(cardID + ".txt");

Here, a customer is created by the non-default constructor shown above (in fact, the default one doesn't exist now) and saved to the file in current directory with the name defined by the customer's cardID (to distinguish between files corresponding to different customers, you are free to change the naming scheme to whatever you like).

By the way, do you really want to keep all records for such kind of application in text files? Generally, databases are used for such purposes, because it is more convenient and secure.

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 write console output to a txt file

You need to do something like this:

PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);

The second statement is the key. It changes the value of the supposedly "final" System.out attribute to be the supplied PrintStream value.

There are analogous methods (setIn and setErr) for changing the standard input and error streams; refer to the java.lang.System javadocs for details.

A more general version of the above is this:

PrintStream out = new PrintStream(
new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);

If append is true, the stream will append to an existing file instead of truncating it. If autoflush is true, the output buffer will be flushed whenever a byte array is written, one of the println methods is called, or a \n is written.


I'd just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.

Alternatively, if you are not "logging" then consider the following:

  • With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.

    $ java MyApp > output.txt   

    For more information, refer to a shell tutorial or manual entry.

  • You could change your application to use an out stream passed as a method parameter or via a singleton or dependency injection rather than writing to System.out.

Changing System.out may cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending on System.out and System.err, but you could be unlucky.)

Creating a text file with java without using absolute path

Your pasted code and the linked question are complete red herrings - they have nothing whatsoever to do with the error you ran into. Also, that protection domain stuff is a hack and you've been told before not to write data files next to your jar files, it's not how OSes (are supposed to) work. Use user.home for this.

There is nothing in this method that explains the question marks - the string, as returned, has plenty of issues (see above), but NOT that it will result in question marks in the output.

Files are fundamentally bytes. Strings are fundamentally characters. Therefore, when you write code that writes a string to a file, some code somewhere is converting chars to bytes.

Make sure the place where that happens includes a charset encoding.

Use the new API (I think you've also been told to do this, by me, in an earlier question of yours) which defaults to UTF-8. Alternatively, specify UTF-8 when you write. Note that the usage of UTF-8 here is about the file name, not the contents of it (as in, if you put persian symbols in the file name, it's not about persian symbols in the contents of the file / in the contents you want to write).

Because you didn't paste the code, I can't give you specific details as there are hundreds of ways to do this, and I do not know which one you used.

To write to a file given a String representing its path:

Path p = Paths.get(completePath);
Files.write("Hello, World!", p);

is all you need. This will write as UTF_8, which can handle persian symbols (because the Files API defaults to UTF-8 if you specify no encoding, unlike e.g. new File, FileOutputStream, FileWriter, etc).

If you're using outdated APIs: new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thePath), StandardCharsets.UTF-8) - but note that this is a resource leak bug unless you add the appropriate try-with-resources.

If you're using FileWriter: FileWriter is broken, never use this class. Use something else.

If you're converting the string on its own, it's str.getBytes(StandardCharsets.UTF_8), not str.getBytes().

How can I update specific parts of a text file in java?

If you are allowed for this project (i.e., not a school assignment), I recommend using JSON, YAML, or XML. There are too many Java libraries to recommend for using these types of files, but you can search "Java JSON library" for example.

First, need to address some issues...

It's not good practice to put Scanner scan = new Scanner(System.in); in a try-with-resource. It will auto-close System.in and won't be useable after being used in your Reader class. Instead, just do this:

Scanner scan = new Scanner(System.in);
Reader reader = new Reader(scan, path, fileWriter, fileReader);

Or, even better, don't pass it to the constructor, but just set scan to it in the constructor as this.scan = new Scanner(System.in);

Next, for fileReader, you can just initialize it similarly as you did for fileWriter:

BufferedReader fileReader = Files.newBufferedReader(path, StandardCharsets.UTF_8);

Next, this line:

BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)

Every time this program is run, this line will overwrite the file to empty, which is probably not what you want. You could add StandardOpenOption.APPEND, but then this means you'll only write to the end of the file.

When you update data, you also have the issue that you'll need to "push" down all of the data that comes after it. For example:

Bobby 1 2 3 4 5
Fred 1 2 3 4 5

If you change the name Bobby to something longer like Mr. President, then it will overwrite the data after it.

While there are different options, the best and simplest is to just read the entire file and store each bit of data in a class (name, scores, etc.) and then close the fileReader.

Then when a user updates some data, change that data (instance variables) in the class and then write all of that data to the file.

Here's some pseudo-code:

class MyProg {
// This could be a Map/HashMap instead.
// See updateData().
public List<Player> players = new ArrayList<>();

public void readData(String filename) throws IOException {
Path path = Paths.get(filename);

try(BufferedReader fileReader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
// Read each Player (using specific format)
// and store in this.players
}
}

public void writeData(String filename) throws IOException {
Path path = Paths.get(filename);

try(BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
// Write each Player from this.players in specific format
}
}

public void updateData() {
// 1. Find user-requested Player from this.players
// 2. Update that specific Player class
// 3. Call writeData()

// If you are familiar with Maps, then it would be faster
// to use a Map/HashMap with the key being the player's name.
}
}

class Player {
public String name;
public int games;
public int goals;
//...
}


Related Topics



Leave a reply



Submit