1. Define the Writerfile class, define the name of the created file, the path, its success, set the file contents and other related functions
public class Writerfile {
Public String Filepath=null;
Public String Filename=null;
Public String Filecontent=null;
Public Boolean success;
Create file path
public void SetFilePath (String s)
{
Filepath=s;
Try
{
File Path=new file (filepath);
Path.mkdir ();
}
catch (Exception ex)
{
}
}
Get file path
Public String GetFilePath ()
{
return filepath;
}
Set file name
public void Setfilename (String strname)
{
Filename=strname;
}
Get file name
Public String GetFileName ()
{
return filename;
}
is successful
Public Boolean issuccess ()
{
return success;
}
Set File contents
public void Setfilecontent (String strcontent)
{
Filecontent=strcontent;
byte content[]=filecontent.getbytes ();
Try
{
File File=new file (filepath,filename);
FileOutputStream in=new fileoutputstream (file);
In.write (content,0,content.length);
In.close ();
Success=true;
}
catch (Exception ex)
{
Success=false;
}
}
}
The above class needs to reference the corresponding package "
Import Java.io.File;
Import Java.io.FileOutputStream;
2. Calling functions
Writerfile wf=new writerfile ();
Wf. Setfilename ("file name such as 2.txt");
Wf. SetFilePath ("File path, such as d:\\");
Wf. Setfilecontent (file contents such as "This is the basic operation of testing Java to read files, such as file name, etc.");
if (WF. Issuccess ())
{
System.out.print ("File creation succeeded!");
}
Else
{
System.out.print ("File creation failed!") ");
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java creating file-related content