Search code examples
javafilebufferedstream

Working with BufferedOutputStream


Im using BufferedOutputStream for writing in a file ,it writes list of files and directories in th specified driver, heres the code:

import java.io.File;
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
public class DirectoryReader {

static int spc_count=-1;

static void Process(File aFile)
{
String s;
Path file =
Paths.get("C:\\Java\\Files1.txt");
try
{
 OutputStream output= new 
 BufferedOutputStream(Files.newOutputStream(file,CREATE));

 spc_count++;
 String spcs = "";
 byte [] data= new byte [2048 * 2048];
 for (int i = 0; i < spc_count; i++)
 spcs += " ";
 if(aFile.isFile())
 {
 System.out.println(spcs + "[FILE] " + aFile.getPath());
 s=aFile.getPath();
 System.out.println(" " + s);
 data = s.getBytes();
 output.write(data);
 output.write(13);
 output.write(10);
 output.flush();
 }
else if (aFile.isDirectory()) {
{
System.out.println(spcs + "[DIR] " + aFile.getPath());
s=aFile.getPath();
data = s.getBytes();
output.write(data);
output.write(13);
output.write(10);
output.flush();
}
File[] listOfFiles = aFile.listFiles();
if(listOfFiles!=null) {
for (int i = 0; i < listOfFiles.length; i++)
Process(listOfFiles[i]);
} else {
System.out.println(spcs + " [ACCESS DENIED]");
}
}
output.close();
spc_count--;
}
catch(Exception e)
    {
    System.out.println("Message: " + e);
    }


}


public static void main(String[] args) {
String nam = "D:\\Notes";
File aFile = new File(nam);
Process(aFile);
}

}

but when I go to see the file , I only find the last file written and sometimes I find mixed words .


Solution

  • You are using recurrent calls to your Process method. This method is creating NEW FILE upon execution, so previous content is simply overriden. I would suggest, that you should create output stream, and pass it as argument to every call Process message. This way, you will provide single output stream for storing data. And the problem will be gone.