In: Computer Science
Here is the complete code for the following problem:
NOTE: If you want to write file in another location, you have to pass whole address along with text file name.
For example; If you look in this code, I just pass the txt file name "suka.txt" in File class, it will write the text file in same folder where is your java code is located
Code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
//this class will show how to write a text to a file
public class WriteFile {
//execution of program starts
public static void main(String[] args) {
//this is the text that we wnat to
write
String data = "Saya suka belajar OOP";
FileWriter fr = null;
//since reading a file can throw
input output exception, we will do inside try catch block
try
{
File file = new
File("suka.txt");
//open the file
in write mode
fr = new
FileWriter(file);;
//write the
data
fr.write(data);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
//close files
try
{
fr.close();
}
catch(IOException ex)
{
System.out.println(ex);
}
}
System.out.println("File written successfully");
}
}
------------------------------------------------------------------------------------------------------
Output:
Check if file exist in file explorer: