SetFileAttributes

本文提供了一个Java程序示例,展示如何设置和修改文件的读写权限及时间戳。程序首先确认文件存在,然后显示原始状态,更新时间戳,并将文件设置为只读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * Set file attributes.
 * 
 * To use the program, specify the name of the file
 * on the command line. for example, to set the attributes
 * for a file called test.tst, use the following command line:
 * 
 *      java SetFileAttributes test.tst
 * 
 */

package FileIO;

import java.io.*;
import java.util.*;

/**
 * @author Administrator
 *
 */
public class SetFileAttributes {
	
	/**
	 * Show a file's read/write status.
	 */
	public static void rwStatus(File f) {
		if (f.canRead())
			System.out.println("  Readable");
		else
			System.out.println("  Not Readable");
		
		if (f.canWrite())
			System.out.println("  Writable");
		else
			System.out.println("  Not Writable");
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// First make sure that a file has been specified.
		if (1 != args.length) {
			System.out.println("Usage: SetFileAttributes filename");
			return;
		}
		
		File f = new File(args[0]);
		
		// Confirm that the file exists.
		if (!f.exists()) {
			System.out.println("File not found.");
			return;
		}
		
		// Display original read/write status and time stamp.
		System.out.println("Original read/write permission and time: ");
		rwStatus(f);
		System.out.println("  Last modified on " + new Date(f.lastModified()));
		System.out.println();
		
		// Update the time stamp.
		long t = Calendar.getInstance().getTimeInMillis();
		if (!f.setLastModified(t))
			System.out.println("Can't set time.");
		
		// Set the file to read-only.
		if (!f.setReadOnly())
			System.out.println("Can't set to read-only.");
		
		System.out.println("Modified read/write permission and time: ");
		rwStatus(f);
		System.out.println("  Last modified on " + new Date(f.lastModified()));
		System.out.println();
		
		// Return to read/write status.
		if (!f.setWritable(true, false))
			System.out.println("Can't return to read/write.");
		System.out.println("Read/Write permissions are now: ");
		rwStatus(f);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值