File createTempFile(String prefix, String suffix,File directory) prefix文件名 suffix文件后缀 directory 文件目录
File file = null; File dir = new File("C:\\Users\\MACHENIKE\\Desktop"); file = File.createTempFile ("createText", ".txt", dir); System.out.println(file.getPath());
源码 分析可知当文件名长度小于3时会抛出异常
public static File createTempFile(String prefix, String suffix, File directory) throws IOException { if (prefix.length() < 3) throw new IllegalArgumentException("Prefix string too short"); if (suffix == null) suffix = ".tmp"; File tmpdir = (directory != null) ? directory : TempDirectory.location(); SecurityManager sm = System.getSecurityManager(); File f; do { f = TempDirectory.generateFile(prefix, suffix, tmpdir); if (sm != null) { try { sm.checkWrite(f.getPath()); } catch (SecurityException se) { // don't reveal temporary directory location if (directory == null) throw new SecurityException("Unable to create temporary file"); throw se; } } } while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0); if (!fs.createFileExclusively(f.getPath())) throw new IOException("Unable to create temporary file"); return f; }
在路径下有create.txt文件则修改,没有就创建
@Test public void file() throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Users\\MACHENIKE\\Desktop\\create.txt")); out.write("hello word"); out.close(); System.out.println("文件创建成功!"); }
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\MACHENIKE\\Desktop\\createText.txt")); String str; while ((str = in.readLine()) != null) { System.out.println(json); }
上面读取文件可能会乱码,需要在读取的时候转换成相应的编码
//一、转换成byte数组 BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\MACHENIKE\\Desktop\\createText.txt")); String str; while ((str = in.readLine()) != null) { byte[] bytes = str.getBytes(); String json = new String(bytes, "UTF-8"); System.out.println(json); } //二、读取时候设置编码 BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\MACHENIKE\\Desktop\\createText.txt"),"UTF-8")); String str; while ((str = in.readLine()) != null) { System.out.println(str); }
File file = new File("C:\\Users\\MACHENIKE\\Desktop\\createText.txt"); if(file.delete()){ System.out.println(file.getName() + " 删除成功!"); }else{ System.out.println("删除失败!"); }
File file = new File("C:\\Users\\MACHENIKE\\Desktop\\nonentity.txt"); System.out.println(file.exists());
File oldName = new File("C:\\Users\\MACHENIKE\\Desktop\\createText.txt");//旧文件 File newName = new File("C:\\Users\\MACHENIKE\\Desktop\\newText.txt");//新文件 if (oldName.renameTo(newName)){ System.out.println("成功"); } else { System.out.println("失败"); }
File file = new File("C:\\Users\\MACHENIKE\\Desktop\\newText.txt"); if (!file.exists() || !file.isFile()) { System.out.println("文件不存在"); } System.out.println(file.length());//单位字节
File file = new File("C:\\Users\\MACHENIKE\\Desktop\\newText.txt"); System.out.println(file.setReadOnly()); //该方法返回true,如果应用程序写入文件,否则该方法返回false。 System.out.println(file.canWrite());