java文件存在
❶ java判斷文件是否存在不存在就創建
用File類中的.exists()方法判斷是否存在
mkdirs創建目錄
createNewFile()創建文件
多看看API文檔
boolean
exists()
測試此抽象路徑名表示的文件或目錄是否存在。
createNewFile()
當且僅當不存在具有此抽象路徑名指定名稱的文件時,不可分地創建一個新的空文件。
boolean
mkdirs()
創建此抽象路徑名指定的目錄,包括所有必需但不存在的父目錄。
❷ 怎麼把指定文件存在指定目錄下java
java寫入文件到指定文件夾的方法主要有兩種:利用PrintStream和利用StringBuffer
例如將文本「I'm the text to be write」寫入到文件夾D:/test下,並命名為test.txt,則兩種方式簡單實現代碼如下:
1. 利用PrintStream寫文件
public void PrintStreamDemo(){
try {
FileOutputStream out=new FileOutputStream("D:/test.txt");
PrintStream p=new PrintStream(out);
p.println("I'm the text to be write");
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
2. 利用StringBuffer寫文件
public void StringBufferDemo() throws IOException{
File file=new File("D:/test.txt");
if(!file.exists())
file.createNewFile();
FileOutputStream out=new FileOutputStream(file,true);
StringBuffer sb=new StringBuffer();
sb.append("I'm the text to be write");
out.write(sb.toString().getBytes("utf-8"));
}
out.close();
}
提示:利用StringBuffer寫文件可以設定使用何種編碼,有效解決中文問題。
❸ java怎麼判斷一個文件是否存在
用java.io.File類的public boolean exists()方法就能判斷,如:
import java.io.*;
public class Demo
{
public static void main(String[] args) throws Exception
{
//將p指定為文件的路徑
String p="test.txt";
File f=new File(p);
if(f.isFile())
{
if(f.exists())
{
System.out.println("文件"+p+"存在。");
}
else
{
System.out.println("文件"+p+"不存在。");
}
}
else
{
System.out.println(p+"不是文件。");
}
}
}
❹ Java中怎樣根據文件的路徑去判斷該文件夾中是否存在該文件
1.File testFile = new File(testFilePath);
if(!testFile .exists()){
testFile.mkdirs();
System.out.println("測試文件夾不存在");
}
2.File testFile = new File(testFilePath);
if(!testFile .exists()){
testFile.createNewFile();
System.out.println("測試文件不存在");
}
java中File類自帶一個檢測方法exists可以判斷文件或文件夾是否存在,一般與mkdirs方法(該方法相較於mkdir可以創建包括父級路徑,推薦使用該方法)或者createNewFile方法合作使用。
1,如果路徑不存在,就創建該路徑
2,如果文件不存在,就新建該文件
❺ java 根據文件名判斷文件是否存在
File類自帶判斷文件(或者路徑)是否存在的方法。舉個例子:
Stringpath="D:\";
Stringfilename="test.txt";
Filefile=newFile(path+filename);
if(file.exists()){
System.out.println("文件"+filename+"存在");
}else{
System.out.println("文件"+filename+"不存在")
}
❻ Java判斷文件目錄以及文件是否存在
近日在項目中遇到一個問題,需要在指定的目錄下面,找到指定的文件。查找相關方法後,特將方法寫出來以便日後用到。 public static File checkExist(String filepath)throwsException{File file=newFile(filepath);if(file.exists()) {//判斷文件目錄的存在System. out .println("文件夾存在!");if(file.isDirectory()){//判斷文件的存在性System. out .println("文件存在!");}else{ file.createNewFile();//創建文件System. out .println("文件不存在,創建文件成功!");}}else{System. out .println("文件夾不存在!"); File file2=newFile(file.getParent()); file2.mkdirs();System. out .println("創建文件夾成功!");if(file.isDirectory()){System. out .println("文件存在!");}else{ file.createNewFile();//創建文件System. .println("文件不存在,創建文件成功!");}}returnfile;}
❼ Java建立文件如果文件存在則不建立
你在創建之前可以加個判斷,判斷文件是否存在,如果存在直接return或者你路徑文件名加1