How to Save a String to a Text File Using Java

How do you write a String to a text file?

Try this:

//Put this at the top of the file:
import java.io.*;
import java.util.*;

BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));

//Add this to write a string to a file
//
try {

out.write("aString\nthis is a\nttest"); //Replace with the string
//you are trying to write
}
catch (IOException e)
{
System.out.println("Exception ");

}
finally
{
out.close();
}

How to save a string to a .txt file in java

Try This:

public static void main(String args[])throws IOException {

File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
}

Read more abut here

Write String to text-file in java

FileWriter fooWriter = new FileWriter(myFoo, false);

// true to append

// false to overwrite;
where myFoo is the File name

See this link

Writing String to Text File

This is the way it is done. The following sample code saves the details to a file upon clicking of the submit button:

Submit = (Button) findViewById(R.id.btnSubmit); //Instantiates the button in the onCreate method 
Submit.setOnClickListener(new OnClickListener(){ //Called when the user clicks on the Submit button

@Override
public void onClick(View v) {
// In this case the text to be written is the selected text in a radio button from radioGroup
int Selection = AttendanceGroup.getCheckedRadioButtonId();

// find the radiobutton by returned id
RadioButton radiobutton = (RadioButton) findViewById(Selection);

// write on SD card file data in the text box
try {

//gets the current date since this is an attendance app.
Calendar c = Calendar.getInstance();
//Formats the date a desired
SimpleDateFormat date = new SimpleDateFormat("dd-MM-yy");
String getDate = date.format(c.getTime());

//writes the text to the file named attendance.txt which is created in the phone.
File myFile = new File("/sdcard/Albanapp/Attendance.txt");
FileWriter fOut = new FileWriter(myFile, true);
fOut.append(getDate + "\t" + getSelectedName.getSelectedItem().toString() + "\t" + radiobutton.getText().toString() + "\n");
fOut.flush();
fOut.close();

//Returns a statment to the user showing if the editing of the attendance.txt file was successful or not.
Toast.makeText(getBaseContext(),"Status Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Attendance cannot be saved",
Toast.LENGTH_SHORT).show();
}
}
});

Hope this helps :)

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

Find words in a text file and save them to a new file using Java

Multiple issues with this code.

Deplorable exception handling

This code, if a problem occurs, will take all useful information about your exception (which is at least 4 things: The exception's type, the exception's message, the stack trace, and the causual chain), and tosses it in the garbage.

You will write bugs. Loads of em. Your assumptions about where your app run will change on you.

Exceptions are crucial in managing this.

Stop writing code like this. The fix is easy, and even reduces and simplifies your code! Simply pile throws Exception at the end of your main declaration (public static void main(String[] args) throws Exception {) and remove the try, the catch, and the return in the catch.

This way, the exception bubbles up to whatever invokes main itself, and that will 'handle' it by printing all the various useful parts and exiting your app. Which is what you want.

charset violations

Files are bags of bytes, but Writer and Reader work in terms of characters. Anytime bytes are converted to characters or vice versa, an encoding is applied. UTF-8 is an encoding. So is ISO-8859-1, MacRoman, CP452, etcetera.

If you don't see the encoding being applied then usually that means 'platform default' is applied and you almost never want that. It leads to code that seems to work fine until you run it elsewhere or on different files and then all hell breaks loose.

The fix is to either use APIs which have baked into their specification that they default to UTF_8 (such as the new Files API), or to explicitly specify. In passing, unfortunately, FileWriter and FileReader are not fit for purpose; do not ever use these classes, they are effectively broken as designed. Their API is also obsolete, there's a newer API.

Using the old APIs, you'd fix it as follows:

new BufferedWriter(new InputStreamWriter(new FileInputStream("path\\file.txt"), StandardCharsets.UTF_8));

Using the new APIs, well, that's a bit more involved, see below.

Resource management violation

When you open resources, you must explicitly close them too. Java is a garbage collected language, but the 'point' of garbage collection is that the JVM will run collection when it deems neccessary, and it might be days before it does. Thus, any object that takes up more than simply memory if you leave it laying about needs explicit closing. "Handles" to files is one such resource: Your OS has a limited supply of these and will flat out refuse to let a process open more files once it has opened a certain amount. Your code opens files but may not close them anymore: If an exception occurs, that br.close() and bw.close() line will never be executed.

Java has a tool for this: Automatic Resource Management (ARM), also called 'try-with-resources'. Replace this:

BufferedWriter bw = ....;
// do stuff with the writer
bw.close();

with:

try (BufferedWriter bw = ....) {
// do stuff with the writer
}

The {} mark where you use the writer: Java ensures that no matter how you 'exit' out of these {}, the resource WILL be closed. Whether you just get to the end of this block, or you return/break/continue out of it, or an exception leads you out of it, the resource is closed.

Searching for strings

regexps is one way, but if you're looking for a specific exact string that's overkill. Strings have a .contains() method.

New API

There's a new API. The old File API has a nasty tendency to just return false when things can't be done instead of telling you about it like 'normal' java APIs. It's also got more flexibility: It can handle such things as managing file ownership, file creation stamps, access control, and links. It also has the nice property that the default charset encoding, if you don't specify anything, is UTF-8 instead of the dreaded and extremely useless 'platform default'.

Backslashes

Not neccessary, even on windows. path/file.txt works just as well. It reads easier and is far more common.

var

You can use var instead of writing out the type a second time which can come in handy. var x = new Foo(); is the same as Foo x = new Foo().

Putting it all together

public class Change {
public static void main(String[] args) throws Exception {
try (
var bw = Files.newBufferedWriter(Paths.get("path/newfile.txt"));
var br = Files.newBufferedReader(Paths.get("path/file.txt"));
) {

String s;
while ((s = br.readLine()) != null) {
if (s.contains("StringToFind")) {
// or: s.matches("^.*String[a-zA-Z]WithRegexpToFind.*$")
bw.write(s + "\n");
}
}
}
}
}


Related Topics



Leave a reply



Submit