0
我試圖通過文件夾和子文件夾來查找包含此短語的文本文件中的短語「測試程序」,並將其替換爲「測試此程序」。我也試圖顯示子文件夾的內容。我可以顯示父文件夾的內容,但不能顯示子文件夾。我也可以編輯第一個文件(Test.txt)的文本,但我想通過搜索父文件夾(Test)而不是訪問此文件來編輯第二個文件(Test1.txt)中的文本直接文件。任何有關如何搜索和編輯文件夾/子文件夾中的特定文本的建議將不勝感激。檢查和替換文件夾和子文件夾中的文本
File f = new File("C:/Test/Test.txt");
FileInputStream fs = null;
InputStreamReader in = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try
{
fs = new FileInputStream(f);
in = new InputStreamReader(fs);
br = new BufferedReader(in);
for (;;)
{
String textinLine = br.readLine();
if (textinLine == null) {
break;
}
sb.append(textinLine);
}
String textToEdit1 = "hello";
int cnt1 = sb.indexOf(textToEdit1);
sb.replace(cnt1, cnt1 + textToEdit1.length(), "hello there");
fs.close();
in.close();
br.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
FileWriter fstream = new FileWriter(f);
BufferedWriter outobj = new BufferedWriter(fstream);
outobj.write(sb.toString());
outobj.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
//搜索文件夾中的文/子
File f1 = new File("C:/Test/Test1/Test1.txt");
FileInputStream fs1 = null;
InputStreamReader in1 = null;
BufferedReader br1 = null;
StringBuffer sb1 = new StringBuffer();
try
{
fs1 = new FileInputStream(f1);
in1 = new InputStreamReader(fs1);
br1 = new BufferedReader(in1);
for (;;)
{
String textinLine1 = br1.readLine();
if (textinLine1 == null) {
break;
}
sb1.append(textinLine1);
String checkWords = "run away";
boolean retVal = textinLine1.contains(checkWords);
}
String textToEdit11 = "test program";
int cnt11 = sb1.indexOf(textToEdit11);
sb1.replace(cnt11, cnt11 + textToEdit11.length(), "test this program");
fs1.close();
in1.close();
br1.close();
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
FileWriter fstream1 = new FileWriter(f1);
BufferedWriter outobj1 = new BufferedWriter(fstream1);
outobj1.write(sb1.toString());
outobj1.close();
}
catch (Exception e1)
{
System.err.println("Error: " + e1.getMessage());
}
File folder1 = new File("C:\\");
File[] filesInDir = folder1.listFiles();
String dirname = "C:\\Test";
File f2 = new File(dirname);
if (f2.isDirectory())
{
System.out.println("Directory of " + dirname);
String[] sR = f2.list();
for (int iR = 0; iR < sR.length; iR++)
{
File f2R = new File(dirname + "/" + sR[iR]);
if (f2R.isDirectory()) {
System.out.println(sR[iR] + " is a directory");
} else {
System.out.println(sR[iR] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}"
對不起,最初沒有說明這一點,但我正在使用Java 6。 – userfl89 2014-10-10 00:34:33