- 浏览: 131756 次
- 性别:
- 来自: 济南
文章分类
最新评论
Java常用文件目录处理代码集
转自:http://junglesong.ycool.com/post.1068267.html
建立文件路径(Constructing a Filename Path)
String path = File.separator + "a" + File.separator + "b";
在文件路径和Url之间进行转换(Converting Between a Filename Path and a URL)
// Create a file object
File file = new File("filename");
// Convert the file object to a URL
URL url = null;
try {
// The file need not exist. It is made into an absolute path
// by prefixing the current working directory
url = file.toURL(); // file:/d:/almanac1.4/java.io/filename
} catch (MalformedURLException e) {
}
// Convert the URL to a file object
file = new File(url.getFile()); // d:/almanac1.4/java.io/filename
// Read the file contents using the URL
try {
// Open an input stream
InputStream is = url.openStream();
// Read from is
is.close();
} catch (IOException e) {
// Could not open the file
}
从相对文件路径取得绝对文件路径(Getting an Absolute Filename Path from a Relative Filename Path)
File file = new File("filename.txt");
file = file.getAbsoluteFile(); // c:\temp\filename.txt
file = new File("dir"+File.separatorChar+"filename.txt");
file = file.getAbsoluteFile(); // c:\temp\dir\filename.txt
file = new File(".."+File.separatorChar+"filename.txt");
file = file.getAbsoluteFile(); // c:\temp\..\filename.txt
// Note that filename.txt does not need to exist
判断是否两个文件路径是否指向同一个文件(Determining If Two Filename Paths Refer to the Same File)
File file1 = new File("./filename");
File file2 = new File("filename");
// Filename paths are not equal
boolean b = file1.equals(file2); // false
// Normalize the paths
try {
file1 = file1.getCanonicalFile(); // c:\almanac1.4\filename
file2 = file2.getCanonicalFile(); // c:\almanac1.4\filename
} catch (IOException e) {
}
// Filename paths are now equal
b = file1.equals(file2); // true
得到文件所在的文件夹名(Getting the Parents of a Filename Path)
// Get the parent of a relative filename path
File file = new File("Ex1.java");
String parentPath = file.getParent(); // null
File parentDir = file.getParentFile(); // null
// Get the parents of an absolute filename path
file = new File("D:\almanac\Ex1.java");
parentPath = file.getParent(); // D:\almanac
parentDir = file.getParentFile(); // D:\almanac
parentPath = parentDir.getParent(); // D:\
parentDir = parentDir.getParentFile(); // D:\
parentPath = parentDir.getParent(); // null
parentDir = parentDir.getParentFile(); // null
判断路径指向的是文件还是目录(Determining If a Filename Path Is a File or a Directory)
File dir = new File("directoryName");
boolean isDir = dir.isDirectory();
if (isDir) {
// dir is a directory
} else {
// dir is a file
}
判断文件或者路径是否存在(Determining If a File or Directory Exists)
boolean exists = (new File("filename")).exists();
if (exists) {
// File or directory exists
} else {
// File or directory does not exist
}
创建文件(Creating a File)
try {
File file = new File("filename");
// Create file if it does not exist
boolean success = file.createNewFile();
if (success) {
// File did not exist and was created
} else {
// File already exists
}
} catch (IOException e) {
}
得到文件的大小(Getting the Size of a File)
File file = new File("infilename");
// Get the number of bytes in the file
long length = file.length();
删除文件(Deleting a File)
boolean success = (new File("filename")).delete();
if (!success) {
// Deletion failed
}
创建临时文件(Creating a Temporary File)
try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}
重命名一个文件或目录(Renaming a File or Directory)
// File (or directory) with old name
File file = new File("oldname");
// File (or directory) with new name
File file2 = new File("newname");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}
移动文件或者目录(Moving a File or Directory to Another Directory)
// File (or directory) to be moved
File file = new File("filename");
// Destination directory
File dir = new File("directoryname");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
// File was not successfully moved
}
取得和修改文件或目录的修改时间(Getting and Setting the Modification Time of a File or Directory)
This example gets the last modified time of a file or directory and then sets it to the current time.
File file = new File("filename");
// Get the last modified time
long modifiedTime = file.lastModified();
// 0L is returned if the file does not exist
// Set the last modified time
long newModifiedTime = System.currentTimeMillis();
boolean success = file.setLastModified(newModifiedTime);
if (!success) {
// operation failed.
}
强制更新硬盘上的文件(Forcing Updates to a File to the Disk)
In some applications, such as transaction processing, it is necessary to ensure that an update has been made to the disk. FileDescriptor.sync() blocks until all changes to a file are written to disk.
try {
// Open or create the output file
FileOutputStream os = new FileOutputStream("outfilename");
FileDescriptor fd = os.getFD();
// Write some data to the stream
byte[] data = new byte[]{(byte)0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE};
os.write(data);
// Flush the data from the streams and writers into system buffers.
// The data may or may not be written to disk.
os.flush();
// Block until the system buffers have been written to disk.
// After this method returns, the data is guaranteed to have
// been written to disk.
fd.sync();
} catch (IOException e) {
}
得到当前的工作目录(Getting the Current Working Directory)
The working directory is the location in the file system from where the java command was invoked.
String curDir = System.getProperty("user.dir");
创建目录(Creating a Directory)
// Create a directory; all ancestor directories must exist
boolean success = (new File("directoryName")).mkdir();
if (!success) {
// Directory creation failed
}
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("directoryName")).mkdirs();
if (!success) {
// Directory creation failed
}
删除目录(Deleting a Directory)
// Delete an empty directory
boolean success = (new File("directoryName")).delete();
if (!success) {
// Deletion failed
}
If the directory is not empty, it is necessary to first recursively delete all files and subdirectories in the directory. Here is a method that will delete a non-empty directory.
// Deletes all files and subdirectories under dir.
// Returns true if all deletions were successful.
// If a deletion fails, the method stops attempting to delete and returns false.
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
列举文件夹中的文件和子目录(Listing the Files or Subdirectories in a Directory)
This example lists the files and subdirectories in a directory. To list all descendant files and subdirectories under a directory, see e33 Traversing the Files and Directories Under a Directory.
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
列举系统根目录下的文件(Listing the File System Roots)
UNIX file systems have a single root, `/'. On Windows, each drive is a root. For example the C drive is represented by the root C:\.
File[] roots = File.listRoots();
for (int i=0; i<roots.length; i++) {
process(roots[i]);
}
遍历目录(Traversing the Files and Directories Under a Directory)
This example implements methods that recursively visits all files and directories under a directory.
// Process all files and directories under dir
public static void visitAllDirsAndFiles(File dir) {
process(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
// Process only directories under dir
public static void visitAllDirs(File dir) {
if (dir.isDirectory()) {
process(dir);
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllDirs(new File(dir, children[i]));
}
}
}
// Process only files under dir
public static void visitAllFiles(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllFiles(new File(dir, children[i]));
}
} else {
process(dir);
}
}
从控制台读入文本(Reading Text from Standard Input)
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (str != null) {
System.out.print("> prompt ");
str = in.readLine();
process(str);
}
} catch (IOException e) {
}
从文件中读入文本(Reading Text from a File)
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}
将文件内容读入一个Byte型数组(Reading a File into a Byte Array)
This example implements a method that reads the entire contents of a file into a byte array.
See also e35 Reading Text from a File.
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
写文件(Writing to a File)
If the file does not already exist, it is automatically created.
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
}
向文件中添加内容(Appending to a File)
try {
BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
out.close();
} catch (IOException e) {
}
使用随即存取文件(Using a Random Access File)
try {
File f = new File("filename");
RandomAccessFile raf = new RandomAccessFile(f, "rw");
// Read a character
char ch = raf.readChar();
// Seek to end of file
raf.seek(f.length());
// Append to the end
raf.writeChars("aString");
raf.close();
} catch (IOException e) {
}
从文件中阅读UTF-8格式的数据(Reading UTF-8 Encoded Data)
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("infilename"), "UTF8"));
String str = in.readLine();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
向文件中写入UTF-8格式的数据(Writing UTF-8 Encoded Data)
try {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("outfilename"), "UTF8"));
out.write(aString);
out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
从文件中阅读ISO Latin-1格式的数据(Reading ISO Latin-1 Encoded Data)
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("infilename"), "8859_1"));
String str = in.readLine();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
向文件中写入ISO Latin-1 格式的数据(Writing ISO Latin-1 Encoded Data)
try {
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("outfilename"), "8859_1"));
out.write(aString);
out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
序列化实体(Serializing an Object)
The object to be serialized must implement java.io.Serializable. This example serializes a javax.swing.JButton object.
See also e45 Deserializing an Object.
Object object = new javax.swing.JButton("push me");
try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}
反序列化实体(Deserializing an Object)
This example deserializes a javax.swing.JButton object.
See also e44 Serializing an Object.
try {
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
javax.swing.JButton button = (javax.swing.JButton) in.readObject();
in.close();
// Get some byte array data
byte[] bytes = getBytesFromFile(file);
// see e36 Reading a File into a Byte Array for the implementation of this method
// Deserialize from a byte array
in = new ObjectInputStream(new ByteArrayInputStream(bytes));
button = (javax.swing.JButton) in.readObject();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
Implementing a Serializable Singleton
By default, the deserialization process creates new instances of classes. This example demonstrates how to customize the deserialization process of a singleton to avoid creating new instances of the singleton.
public class MySingleton implements Serializable {
static MySingleton singleton = new MySingleton();
private MySingleton() {
}
// This method is called immediately after an object of this class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return singleton;
}
}
Tokenizing Java Source Code
The StreamTokenizer can be used for simple parsing of a Java source file into tokens. The tokenizer can be aware of Java-style comments and ignore them. It is also aware of Java quoting and escaping rules.
try {
// Create the tokenizer to read from a file
FileReader rd = new FileReader("filename.java");
StreamTokenizer st = new StreamTokenizer(rd);
// Prepare the tokenizer for Java-style tokenizing rules
st.parseNumbers();
st.wordChars('_', '_');
st.eolIsSignificant(true);
// If whitespace is not to be discarded, make this call
st.ordinaryChars(0, ' ');
// These calls caused comments to be discarded
st.slashSlashComments(true);
st.slashStarComments(true);
// Parse the file
int token = st.nextToken();
while (token != StreamTokenizer.TT_EOF) {
token = st.nextToken();
switch (token) {
case StreamTokenizer.TT_NUMBER:
// A number was found; the value is in nval
double num = st.nval;
break;
case StreamTokenizer.TT_WORD:
// A word was found; the value is in sval
String word = st.sval;
break;
case '"':
// A double-quoted string was found; sval contains the contents
String dquoteVal = st.sval;
break;
case '\'':
// A single-quoted string was found; sval contains the contents
String squoteVal = st.sval;
break;
case StreamTokenizer.TT_EOL:
// End of line character found
break;
case StreamTokenizer.TT_EOF:
// End of file has been reached
break;
default:
// A regular character was found; the value is the token itself
char ch = (char)st.ttype;
break;
}
}
rd.close();
} catch (IOException e) {
}
相关推荐
此外,文件可能还会包含异常处理(try-catch-finally语句)、接口和抽象类的使用示例,这些都是Java中重要的错误管理和设计模式的基础。 在集合框架方面,文件可能涵盖了ArrayList、LinkedList、HashMap、HashSet等...
"Java常用代码全集.zip"这个压缩包文件很可能包含了一整套实用的Java代码示例,旨在帮助开发者更好地理解和掌握Java编程的核心概念、语法以及常见问题的解决方案。 文档"Java常用代码全集.doc"可能涵盖了以下几个...
《Java开发常用代码全集》是一个集合了Java编程语言中常用代码片段的资源库,旨在为Java开发者提供方便快捷的参考。这个压缩包文件“Java开发常用代码全集.7z”包含了各种实用的Java代码示例,是学习和工作中不可或...
这个"Java开发常用代码全集.zip"压缩包显然包含了Java编程中常用的代码片段和示例,对于初学者和经验丰富的开发者来说都是一个宝贵的资源。让我们深入探讨一下这个资源可能涵盖的一些关键知识点。 1. **基础语法**...
`java的jdbc连接.txt`可能包含了如何加载驱动、建立数据库连接、执行SQL语句以及处理结果集的代码。 6. **字符串解析**:在Java中,字符串是不可变对象,但可以通过`StringTokenizer`、`Pattern`和`Matcher`类进行...
收集了一些实用的Java类库文件集,全部都是Java源文件,比如加密解密类、文件帮助类、ftp二进制与ascii传输方式区别、文件上传类、MD5加密类、文件滤镜类、数据库连接类和操作类、StringHelper字符串处理类、功能...
本压缩包文件"Java 常用数值算法集"很可能是为了帮助开发者们快速理解和实现常见的数值计算方法。下面,我们将详细探讨几个Java中常用到的数值算法。 1. **线性代数运算**:包括矩阵运算、向量运算等。例如,求解...
### Java对文件进行简单处理 #### 核心知识点解析 本文将基于提供的代码示例...通过这个简单的示例,我们可以了解到Java中文件处理的基本步骤和常用类库的使用方法,这对于实际开发中处理文件相关的任务非常有帮助。
【Java学习代码集】是一个集合了Java编程语言学习过程中常用示例代码的资源包,主要针对初学者和希望深入理解Java SE(标准版)的开发者。这个资源包可能包含了宋红康老师在尚硅谷教育机构讲解Java课程时使用的实例...
Java图像处理源代码是开发者们在进行图形用户界面(GUI)开发时常用的一种工具,尤其在需要对图像进行各种操作,如裁剪、旋转、滤镜应用等场景下。这个资源提供了一个完整的Java图像处理功能集,旨在方便开发人员...
通过分析和学习这些Java记事本代码,初学者可以掌握Java GUI编程、文件操作、事件处理等核心技能,并逐步提高编程能力。同时,对比不同人的实现方式,有助于理解问题的不同解法,培养代码优化和设计思维。
在Java中,可以使用二维数组来表示雷区,通过算法来计算每个格子周围的雷数。游戏状态的更新和用户交互是通过事件驱动模型实现的。 3. **聊天程序**:一个简单的聊天程序可能涉及网络编程,如Socket通信,实现...
### Java压缩文件代码详解 #### 一、概述 在日常的软件开发过程中,对文件进行压缩处理是一项常见的需求。无论是为了节省存储空间还是提高传输效率,掌握如何使用Java语言进行文件压缩都是非常重要的技能之一。本...
下面我们将详细探讨Java中28个常用的工具类,主要涉及`IO`相关的开发工具。 1. **java.lang.Math**:这个类提供了许多基础数学函数,如求平方根、最大值、最小值、随机数生成等。 2. **java.util.Arrays**:用于...
Java中的`Charset`类处理字符编码,组件集可能提供了处理UTF-8、GBK等常见编码的工具,以避免乱码问题。 7. **异常处理**:在进行文件操作时,必须处理可能出现的异常,如`FileNotFoundException`、`IOException`等...
在Java中处理中文字符时,理解并正确应用字符编码转换至关重要。开发者应确保所有输入输出的编码一致,特别是在不同编码环境下工作时,要谨慎进行编码转换,避免因编码不匹配导致的数据丢失或乱码问题。通过掌握上述...
这个名为“Java基本常用代码示例”的资源集包含了Java程序设计中的一些基础和常见代码片段,对于初学者或需要复习基本概念的开发者来说非常有用。下面我们将深入探讨这些标签所涵盖的Java基本知识点。 1. **数据...
12. **设计模式**:书中可能包含一些基于经典设计模式的案例,如单例模式、工厂模式、观察者模式等,这些都是软件工程中常用的最佳实践。 通过《Java案例开发集锦》的源代码,读者不仅可以深入学习Java语言,还能...
总的来说,处理Java中CSV文件的中文乱码问题主要涉及正确设置字符编码,而给定的.NET DLL文件与此问题的解决没有直接关联。如果你在.NET环境中遇到类似问题,可以参考.NET的编码处理方式,或者寻找适合的.NET库来...
"Java常用代码整理"这个主题涵盖了Java开发中的诸多常见技术点和实用代码片段,旨在帮助开发者提升工作效率。以下是对这些知识点的详细阐述: 1. **基础语法**:Java的基础语法包括数据类型(如整型、浮点型、字符...