【发布时间】:2013-06-13 13:16:45
【问题描述】:
我是 Java 新手,一直在尝试实现一个创建目录及其各自文件的函数。其中一个文件是“mapping.txt”,它位于名为 NodeA 的文件夹中。 mapping.txt 的内容是 NodeA 的绝对路径。
请在下面找到我尝试过的代码。为了更好地理解,我在所有可能的地方发表了评论。我想知道我无法在文件中写入的原因。任何帮助将不胜感激。
//-------------------------- To create Node and their respective Files ------------------------------------------------------
for(int j=0;j<alpha.length;j++){ //alpha is a String array which contains {"A","B","C","D"}
node_directory=Node.concat(alpha[j]); // nodde_directory is "C:\Users\Desktop\Node. I concat A,B,C and D to create different directories.
File dir = new File(node_directory);
if(!dir.exists()){
dir.mkdirs();
}
System.out.println("Path: \n" +dir.getAbsolutePath());
System.out.println();
List<String> fileList = Arrays.asList(files); // files is an array of string containing "mapping" and "data".
Iterator <String> iter = fileList.iterator(); //I traverse through the list.
while(iter.hasNext()){
File next_file = new File(node_directory+"\\"+iter.next()+".txt"); //while traversing, I append the current "iter.next" to "node_directory" and append ".txt" to create files.
System.out.println("The Files are: \n" +next_file);
System.out.println();
// I created the Directories, mapping and data Files for each directory.
/*I am stuck here, as it is not writing the path in the mapping File */
if(iter.next()=="mapping"){ // I check if iter.next is mapping, so that i can write in the mapping file, the path of Folder containing mapping file.
BufferedWriter br = new BufferedWriter(new FileWriter(next_file));
br.write(next_file.getAbsolutePath());
}
if(!next_file.exists()){
System.out.println(next_file.createNewFile());
}
我意识到发生了什么。因为我正在通过列表遍历字符串数组。问题出现在这里:
next_file = new File(node_directory+"\\"+iter.next()+".txt"); // This line creates files by appending the required data. Since iter.next() returns all the Files in one go,
BufferedWriter br = new BufferedWriter(new FileWriter(next_file));
br.write(dir.getAbsolutePath());
next_file 具有一次创建的所有文件。我需要知道创建后如何检查每个文件,以便编辑文件。
谢谢。
【问题讨论】:
-
结果与您的预期有何不同?
-
我试过上面的方法还是不写。该文件为空。我尝试更改项目并尝试但结果相同。
-
提示:添加 @AdrianJandl(或任何人 -
@很重要)以确保他们收到通知新评论。 -
@AdrianJandl 当然。我会跟着
-
@AdrianJandl 我调试代码。当我比较时,{iter.next()=="mapping"} 我试图打印 iter.next() 的内容,结果发现它是完整的字符串数组,即“映射”和“数据” .但我想先遍历并检查“映射”,然后再检查“数据”。现在,我不知道如何进一步进行