java fundação: 13, os métodos da classe de arquivo comumente usados tem? (Com exemplos de código)

Quais são os métodos de arquivo comum?

1, o método de construção comum

(1) do arquivo público (nome de caminho da corda ); // estrutura de caminho absoluto
(2) pública do ficheiro (progenitor corda , String criança); // estrutura caminho relativo
(3) Ficheiro pública (pai do ficheiro , String criança); // se há instância pai, criado pela primeira vez. Em seguida, a configuração do percurso relativo.


public class demo02File {
	public static void main(String[] args) {
		String fatherPath = "D:/other";
		String name = "1.jpg";
		
		// 相对路径构造
		File src1 = new File(fatherPath, name);
		File src2 = new File(new File(fatherPath), "2.jpg");
		
		// 绝对路径构造
		File src3=new File("D:/other/3.jpg");
		
		//没有盘符:以user.dir构建
		File src4= new File("4.jpg");
		System.out.println(src4.getName());
		System.out.println(src4.getPath());
		System.out.println(src4.getAbsolutePath());
		
		//.表示当前路径
		File src5= new File(".");
		System.out.println(src5.getName());
		System.out.println(src5.getPath());
		System.out.println(src5.getAbsolutePath());
	}
}

O código executado resultados:

4.jpg
4.jpg
D: \ mywork \ linlinjava \ javalearnig \ JavaStudy \ 4.jpg
.
.
D: \ mywork \ linlinjava \ javalearnig \ JavaStudy.

2, um método para obter informações

getPath (): caminho do arquivo get
getName (): obter o último nome da camada, nome do documento
getParent (): o caminho para se livrar da última camada, esse arquivo diretório pai
getParentFile (): obter o novo caminho do arquivo pai

		String fatherPath = "D:/other";
		String name = "1.jpg";

		File src1 = new File(fatherPath, name);
		System.out.println("文件路径:" + src1.getPath());
		System.out.println("文件名:" + src1.getName());
		System.out.println("文件上层目录:" + src1.getParent());
		File file1 = src1.getParentFile();// 得到父类路径文件的新对象
		//String[] filesName = file1.list();// 返回路径下文件名的String数组
		//File[] files = file1.listFiles();//获取路径下文件组成的File数组

3, o método de determinação

isDirectory () se a pasta
isFile () se um arquivo
existe () caminho existe
canWrite () é gravável
canRead () é legível
comprimento () tamanho do arquivo? Ele pode ser usado para determinar se um arquivo, pasta, comprimento 0

		String fatherPath = "D:/other";
		String name = "1.jpg";
		File src1 = new File(fatherPath);
		File src2 = new File(fatherPath, name);
		System.out.println("是否存在?  "+src1.exists());
		System.out.println("是否是文件夹?  "+src1.isDirectory());
		System.out.println("是否是文件?  "+src2.isFile());
		System.out.println("文件是否可写? " + src2.canWrite());
		System.out.println("文件是否可读? " + src2.canRead());
		System.out.println("是否是绝对路径? " + src1.isAbsolute());
		System.out.println("文件长度?  "+src1.length());// 文件的长度(字节数),文件夹长度为0,只有文件可以读取长度

4, criar / apagar arquivos

CreateNewFile (); criar um arquivo
delete (); apagar arquivos
createTempFile (); criar um arquivo temporário
tempFile.deleteOnExit (); arquivos temporários são automaticamente eliminados após o programa termina

	public static void test3() throws IOException, InterruptedException {
		String path = "D:/other/0.jpg";
		File f1 = new File(path);
		if (!f1.exists()) {
			boolean flag = f1.createNewFile();
			System.out.println(flag ? "创建成功" : "创建失败");
		} else {
			System.out.println("文件已存在!");
		}
		boolean flag = f1.delete();
		System.out.println(flag ? "删除成功" : "删除失败");
		//临时文件.
		File tempFile=File.createTempFile("tes", ".temp", new File("D:/other"));
		Thread.sleep(2000);
		tempFile.deleteOnExit();//程序退出后自动删除
		
	}

5, método de operação de diretório

mkdir () Crie uma nova pasta, você só pode criar um
mkdirs () para criar uma nova pasta, você pode multi-camada
list (): retorna o nome da matriz do caminho para o arquivo ou pasta
ListFiles (): Retorna o próximo arquivo ou o caminho do arquivo uma variedade de pasta de arquivo

/**
*代码功能:输出文件夹下的文件名称。
*输出文件夹下的文件路径。
*输出文件夹中的txt文件路径
**/
public class demo04File {

	public static void main(String[] args) {
		String path = "D:/other/test/mytest";
		File f1 = new File(path);
		f1.mkdir();// 创建目录,必须确保父目录存在,否则失败
		f1.mkdirs();// 创建目录,如果父目录不存在,一同创建
		if (f1.exists()) {
			System.out.println("=====子目录||子文件====");
			String[] names = f1.list();
			for (String temp : names) {
				System.out.println(temp);
			}
			
			System.out.println("=====子目录||子文件的file对象====");
			File[] files=f1.listFiles();
			for(File temp:files){
				System.out.println(temp.getAbsolutePath());
			}
			
			System.out.println("=====子目录||文件txt对象====");
			//命令设计模式
			File[] files1=f1.listFiles(new FilenameFilter() {
				/**
				 * dir代表f1
				 */
				@Override
				public boolean accept(File dir, String name) {
					return new File(dir,name).isFile()&& name.endsWith(".txt");
				}
			});
			for(File temp:files1){
				System.out.println(temp.getAbsolutePath());
			}
		}
	}
}

Código é executado resultados:
=subdiretório Sub-file ||
1.docx
2.mpp
3.xlsx
4.txt
=sub-arquivos de arquivo objeto subdiretório ||
D: \ outro \ teste \ mytest \ 1.docx
D: \ outro \ teste \ mytest \ 2.mpp
D: \ outro \ teste \ mytest \ 3.xlsx
D: \ outro \ teste \ mytest \ 4.txt
=Txt objetos subdiretório ||
D: \ outro \ teste \ mytest \ 4.txt

Publicado 57 artigos originais · ganhou elogios 13 · vista 1132

Acho que você gosta

Origin blog.csdn.net/weixin_42924812/article/details/105053590
Recomendado
Clasificación