只需要调用该类的一个方法createNewFile(),但是在实际操作中需要注意一些事项,如判断文件是否存在,以及如何向新建文件中写入数据等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import java.io.*; public class CreateNewFile{ //该方法用于创建文件,参数分别是文件路径和文件名、文件内容,如:myfile.doc HelloJava! public void createNewFile(String fileDirectoryAndName,String fileContent){ try { String fileName = fileDirectoryAndName File myFile = new File(fileName); //创建File对象,参数为String类型,表示目录名 //判断文件是否存在,如不存在则调用createNewFile()创建新目录,否则跳至异常处理代码 if (!myFile.exists()) myFile.createNewFile(); else //如果不存在则扔出异常 throw new Exception( "The new file already exists!" ); //下面把数据写入创建的文件,首先新建文件名为参数创建FileWriter对象 FileWriter resultFile = new FileWriter(myFile); //把该对象包装进PrinterWriter对象 PrintWriter myNewFile = new PrintWriter(resultFile); //再通过PrinterWriter对象的println()方法把字符串数据写入新建文件 myNewFile.println(fileContent); resultFile.close(); //关闭文件写入流 } catch (Exception ex){ System.out.println( "无法创建新文件!" ); ex.printStackTrace(); } } public static void main(String[] args){ //创建类的对象并调用该对象的createNewFile()方法,创建新文件并写入数据 CreateNewFile createFile = new CreateNewFile(); createFile.createNewFile(args[ 0 ],args[ 1 ]); } } |
执行该程序,在执行代码后直接输入两个参数,第一个参数是文件名,此时需要注明文件类型,这里创建的word文档;第二个参数是文件的内容,该参数是一个字符串数据。
如:myfile.doc HelloJava!
注意:在通过文件路径和文件创建File时的分隔符可以为“//”或者File.separator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class FileDemo { public static void main(String[] args){ //构造函数File(String pathname) File f1 = new File( "c:\\abc\\1.txt" ); //File(String parent,String child) File f2 = new File( "c:\\abc" , "2.txt" ); //File(File parent,String child) File f3 = new File( "c:" +File.separator+ "abc" ); //separator 跨平台分隔符 File f4 = new File(f3, "3.txt" ); System.out.println(f1); //c:\abc\1.txt } } |
以下代码包括了File的创建以及读写。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
public class Test { public static void main(String[] args) { String lujing = "d:\\test\\ss\\ss.txt" ; File file = new File(lujing); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter fw = new FileWriter(file, true ); BufferedWriter bw = new BufferedWriter(fw); bw.write( "kingid" ); bw.flush(); bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } try { FileReader fr = new FileReader(file); BufferedReader bReader = new BufferedReader(fr); String string = bReader.readLine(); System.out.println(string); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
到此这篇关于Java利用File类创建文件的示例代码的文章就介绍到这了,更多相关Java File类创建文件内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/iteye_6153/article/details/82648854