简单:我如何读取Java中目录的内容,并将该数据保存在某种数组或变量中?其次,我如何用Java打开外部文件?
答案 0 :(得分:11)
您可以使用java IO API。具体为java.io.File
,java.io.BufferedReader
,java.io.BufferedWriter
等。
假设打开你的意思是打开文件进行阅读。另外,为了更好地理解Java I / O功能,请查看以下链接:http://download.oracle.com/javase/tutorial/essential/io/
检查以下代码。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileIO
{
public static void main(String[] args)
{
File file = new File("c:/temp/");
// Reading directory contents
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
// Reading conetent
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("c:/temp/test.txt"));
String line = null;
while(true)
{
line = reader.readLine();
if(line == null)
break;
System.out.println(line);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(reader != null)
{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
答案 1 :(得分:2)
您可以使用课程java.io.File来完成此操作。文件是文件和目录路径名的抽象表示。您可以使用File.list()方法检索其中的文件/目录列表。
答案 2 :(得分:2)
还有Commons IO package,它有各种操作文件和目录的方法。
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
public class CommonsIO
{
public static void main( String[] args )
{
// Read the contents of a file into a String
try {
String contents = FileUtils.readFileToString( new File( "/etc/mtab" ) );
} catch (IOException e) {
e.printStackTrace();
}
// Get a Collection of files in a directory without looking in subdirectories
Collection<File> files = FileUtils.listFiles( new File( "/home/ross/tmp" ), FileFilterUtils.trueFileFilter(), null );
for ( File f : files ) {
System.out.println( f.getName() );
}
}
}
答案 3 :(得分:1)
public class StackOverflow {
public static void main(String[] sr) throws IOException{
//Read a folder and files in it
File f = new File("D:/workspace");
if(!f.exists())
System.out.println("No File/Dir");
if(f.isDirectory()){// a directory!
for(File file :f.listFiles()){
System.out.println(file.getName());
}
}
//Read a file an save content to a StringBuiilder
File f1 = new File("D:/workspace/so.txt");
BufferedReader br = new BufferedReader(new FileReader(f1));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
sb.append(line+"\n");
System.out.println(sb);
}
}