I have this Method that Lists the Files in a Directory and I need to write the same to a file. Apparently my
System.out.println();
is able to list the files and their Sizes and the Dates they were Modified. But My bufferedWriter Does not write Anything in the File. Here is My Method;
public void walk( String path, int limit ) throws IOException {
File root = new File( path );
File[] list = root.listFiles();
File rep = new File("report.txt");
SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yyyy HH:mm:ss");
if (list == null) return;
long size;
BufferedWriter bw = new BufferedWriter(new FileWriter(rep));
for ( File f : list ) {
size = f.length()/1000/1000;
if ( f.isDirectory() ) {
walk( f.getAbsolutePath(), limit );
}
else {
if(size >= limit){
System.out.println( "File:" + f.getAbsoluteFile() + " " + size + "MB Last Modified Date: " + sdf.format(f.lastModified()));
bw.write("File:" + f.getAbsoluteFile() + " " + size + "MB Last Modified Date: " + sdf.format(f.lastModified()) + "\n");
}
}
}
bw.close();
}
What Am I Missing? I need to write the Out to the File report.txt but the file is empty.
I think it's because you're trying to open multiple buffered writers to the same file when it's calling itself through recursion. Try creating your writer outside of this method and pass it in as a parameter.
Example
public void myCallingMethod() throws IOException{
File rep = new File("report.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(rep));
walk("my/path", 4, bw);
bw.close();
}
Here's the code which might solve your problem.
I tried the same.
public class example {
public static void main(String[] args) throws IOException {
// Directory path here
String path = "C:\\";
SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yyyy HH:mm:ss");
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
File file = new File("report.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
long size;
int limit = 2;
for (File f : listOfFiles) {
size = f.length() / 1000 / 1000;
if (size >= limit) {
System.out.println("File:" + f.getAbsoluteFile() + " " + size
+ "MB Last Modified Date: "
+ sdf.format(f.lastModified()));
bw.write("File:" + f.getAbsoluteFile() + " " + size
+ "MB Last Modified Date: "
+ sdf.format(f.lastModified()));
}
}
bw.close();
}
}
try to call the flush method after you called the write methode like:
bw.write("File:" + f.getAbsoluteFile() + " " + size + "MB Last Modified Date: " + sdf.format(f.lastModified()) + "\n");
bw.flush();
The flush method flushes your stream to your file
Define a variable like this
StringBuilder fileData = new StringBuilder();
And replace
bw.write("File:" + f.getAbsoluteFile() + " " + size + "MB Last Modified Date: " + sdf.format(f.lastModified()) + "\n");
bw.flush();
With
fileData.append("File:").append(f.getAbsoluteFile()).append(" ").append(size)
.append("MB Last Modified Date: ").append(sdf.format(f.lastModified()))
.append("\n") ;
And after the for loop write fileData to file
bw.write(fileData.toString());
bw.close();
You need to do a java.io.BufferedWriter#flush() before the close.
Related
I am trying to write a data from database to a csv file via java thread. For writing i am making use of OPENCSV jar. The problem i am facing is that sometimes in csv file values get corrupted like shown below in line 1 and 4.
I have no idea as to why this is happening. Values coming from the database are all ok (as can be seen in the logs) but in csv file its not.
[E[EcoUnit 01] [Segment B/1] [2017-12-29 22:13:23.047] [ventilation air humidity] [70.18]
[EcoUnit 01] [Segment B/1] [2017-10-25 22:21:36.583] [ventilation air humidity] [69.65]
[EcoUnit 01] [Segment B/1] [2017-10-25 22:22:36.59] [ventilation air humidity] [69.33]
[EcoUnit 01] [Segment B/017-11-14 12:02:48.013] [ventilation fan] [30]
I would be really grateful if anyone can let me suggest why this is happening.
Code is as follows: -
List<String> values = new ArrayList<String>();
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
writer.writeNext(values.toArray(new String[]{}));
Adding complete code of the function responsible for creating file and writing into it.
public void createAndFillFile(String startDateStr, String endDateStr, int fileNumber,SolrDocumentList results){
try{
String startDateParts[] = startDateStr.split(" ");
String startDate = startDateParts[0];
String endDateParts[] = endDateStr.split(" ");
String endDate = endDateParts[0];
if(fileNumber == 1){
Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
String currentDate = dateFormat.format(date); //This line can be removed and in below line directly can be used
zipFile = currentDate + ".zip";
dir = new File("C:" + File.separator + "EcotronDownloadable" + File.separator + currentDate);
dir.mkdir();
path = dir.getAbsolutePath() + File.separator ;
file = new File(path+ startDate + "_" + endDate + "_" + fileNumber + ".csv");
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
}
synchronized(file){
for (SolrDocument doc : results) {
List<String> values = new ArrayList<String>();
Thread.sleep(1);
long fileLength = file.length();
if(fileLength<maxFileSize){
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
//log.trace(values);
writer.writeNext(values.toArray(new String[]{}));
}
else{
fw.flush();
fw.close();
// writer.close();
j = j + 1;
file = new File(path + startDate + "_" + endDate + "_" + j + ".csv") ;
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
//log.trace(values);
writer.writeNext(values.toArray(new String[]{}));
}
}
}
// fw.flush();
// fw.close();
// writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
``
You might have two FileWriter instances (in different threads) pointing to the same file and writing at same time.
try this:
synchronized (file)
{
List<String> values = new ArrayList<String>();
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
writer.writeNext(values.toArray(new String[]{}));
}
I want to write to a file in Android, but it results in the following error:
java.lang.IllegalArgumentException: File C:/Users/Senior/Downloads/Gps_location-master/DenverCrimeDataVisualization/app/src/main/res/raw/neighborhood_id_location.json contains a path separator
private void writeToFile() {
try {
OutputStreamWriter outputStreamWriter =
new OutputStreamWriter(new FileOutputStream(new File(getExternalFilesDir(null), "neighborhood_id_location.json")));
outputStreamWriter.write("[");
for (int i = 0; i < geo_lat.length; i++) {
// Maybe:
outputStreamWriter.write("{\"lat\" : " + geo_lat[0] + ", \"lng\" : " + geo_lon[0] + "}");
// Or:
}
outputStreamWriter.write("]");
outputStreamWriter.close();
outputStreamWriter.write("["+"{"+"Latitude" + geo_lat[0] + "," +"Longtitude"+ geo_lon[0] +"}" +"]");
outputStreamWriter.close();
}
Hello i`ve made a program where i unmarshall XML file, get those informations and use them for connecting to server and move files to another folder.
The program goes like this:
1.get the informations from xml
2.connect and upload them to server
3.move the files that have been uploaded to another folder locally.
The problem is when i put Object and method of Upload. The upload is okay, the files are uploaded, new folders are created for files to move there, but the files dont move, they are in the same directory.
If i put Move object and method above Upload its opposite. The files are moved to another folder(locally) but they are not uploaded...
What can be the problem and how to fix this?
Thank you!
Here is my method for marsh and there i use both methods(upload and move):
public void unmarshallList() {
try {
JAXBContext jc = JAXBContext.newInstance(ListNodes.class);
Unmarshaller ums = jc.createUnmarshaller();
ListNodes ln = (ListNodes) ums.unmarshal(new File("C:\\Users\\Desktop\\marshList.xml"));
System.out.println("INFORMATIONS");
System.out.println("-------------------------------");
for (Node p : ln.getListNode()) {
System.out.println("Hostname: " + p.getHostname());
System.out.println("Username: " + p.getUsername());
System.out.println("Password: " + p.getPassword());
System.out.println("Port: " + p.getPort());
System.out.println("Pc Directory: " + p.getPcDirectory());
System.out.println("Node Directory: " + p.getNodeDirectory());
System.out.println("Time interval: " + p.getTimeInterval());
System.out.println("Move Directory" + p.getMoveDir());
System.out.println("-------------------------------");
Upload up = new Upload();
up.connection(p.getHostname(), p.getPort(), p.getUsername(), p.getPassword(), p.getNodeDirectory(), p.getPcDirectory(), p.getTimeInterval(), p.getMoveDir());
Move mv = new Move();
mv.moveFiles(p.getPcDirectory(), p.getMoveDir());
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
And here is my move method:
public static void moveFiles (String oldLocation, String newLocation) {
File source = new File(oldLocation);
File dest = new File(newLocation);
new File(newLocation).mkdir();
File[] files = source.listFiles();
for (File file : source.listFiles()) {
System.out.println(source + "\\" + file.getName());
String x = (source + "\\" + file.getName());
String y = (dest + "\\" + file.getName());
File f1 = new File(x);
f1.renameTo(new File(y));
System.out.println("This file is moved "+x );
}
System.out.println("The files are moved" );
}
And here is the upload method:
private static void recursiveFolderUpload(String sourcePath, String
destinationPath) throws SftpException, FileNotFoundException {
File sourceFile = new File(sourcePath);
if (sourceFile.isFile()) {
// copy if it is a file
channelSftp.cd(destinationPath);
if (!sourceFile.getName().endsWith(".xml"));
channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
} else {
System.out.println("inside " + sourceFile.getName());
File[] files = sourceFile.listFiles();
if (files != null && !sourceFile.getName().endsWith(".xml")) {
channelSftp.cd(destinationPath);
SftpATTRS attrs = null;
// check if the directory is already existing
try {
attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
} catch (Exception e) {
System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
}
// else create a directory
if (attrs != null) {
System.out.println("Directory exists IsDir=" + attrs.isDir());
} else {
System.out.println("Creating dir " + sourceFile.getName());
channelSftp.mkdir(sourceFile.getName());
}
for (File f: files) {
recursiveFolderUpload(f.getAbsolutePath(), destinationPath + "/" + sourceFile.getName());
}
}
}
My guess would be the InputStream of the source file is not closed.
I'd try
InputStream in = new FileInputStream(sourceFile)
try {
channelSftp.put(in, sourceFile.getName(), ChannelSftp.OVERWRITE);
} finally {
in.close();
}
or another way
try (InputStream in = new FileInputStream(sourceFile)) {
channelSftp.put(in, sourceFile.getName(), ChannelSftp.OVERWRITE);
}
which closes the InputStream uppon exiting the try statement.
However - without debugging / any exception message it is almost impossible to be sure
I'm pretty new here, and have been following all I could find on getting my program to append a series of numbers (determined from how often a button was pressed) to a .txt file whenever a timer runs out, but to no avail-I'm not sure what I'm missing...the app starts out by creating a .txt file in the downloads folder with a template in it:
String initialTemplate ="\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\"";
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, filename+".txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(initialTemplate.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And then when a countdowntimer object finishes and restarts/ends, it triggers the class writeresults() to append the values:
if (CountsRemaining < 1){
textViewTime.setText("00:00:00");
cancel();
writeResults();
finishcount();
} else {
//append data
writeResults();
//Clear all variables
clearCounts();
start();
}
And the important part, to actually write the data, which is what isn't working:
public void writeResults(){
String Message = Count1 + ", " + Count2 + ", " + Count3 + ", " + Count4 + ", " + Count5 + ", " +
Count6 + ", " + Count7 + ", " + Count8 + ", " + Count9 + ", " + Count10 + ", " + Count11 + Count12;
FileWriter writer;
try {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File (path + filename+".txt");
writer = new FileWriter(file, true);
writer.append(Message);
writer.append("this is a writing test message");
writer.close();
Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Any idea what I might be missing? Parameters?
The problem is in this line:
File file = new File (path + filename+".txt");
It should be like this, if you look at your first code, when creating file:
File file = new File (path, filename+".txt");
I have a linux java program that is reading and writing to a CIFS mounted Windows file share. See code snippet at bottom.
After execution, there are files named "cifs*" left in the directory. If the target directory is on the local file system, the code works like a champ. However, if the target directory is a CIFS mounted Windows file share, I get the left-over files. I'm not sure what configuration changes I need to make to fix. Any help is greatly appreciated.
FileRenameMutex myFileRenameMutex = new FileRenameMutex("/WindowsMount/MoveLock");
class FileRenameMutex
{
// global variables
String lockFileBasename;
String unusedExtension = "_Unused";
String unusedFilename;
String inUseFilename;
String localMachineAddress;
String formattedTime;
// log4j logger for this class
public static Logger logMutex = Logger.getLogger(FileRenameMutex.class.getName());
public FileRenameMutex(String _lockFileBase) {
this.lockFileBasename = _lockFileBase;
logMutex.debug("FileRenameMutex: Constructor, with file " + lockFileBasename + " user = " + System.getProperty("user.name"));
try {
localMachineAddress = InetAddress.getLocalHost().getHostAddress();
//localMachineAddress = InetAddress.getLocalHost().getHostName();
} catch ( Exception e ) {
localMachineAddress = "UNKNOWN_HOST";
logMutex.error(" Could not determine host address. " + e.getMessage());
}
// set the file names
unusedFilename = lockFileBasename + unusedExtension;
inUseFilename = lockFileBasename + "_" + localMachineAddress;
logMutex.debug(" Local machine = " + localMachineAddress);
logMutex.debug(" Unused file name = " + this.unusedFilename);
logMutex.debug(" In Use file name = " + this.inUseFilename);
}
public boolean tryAcquire() throws InterruptedException {
boolean returnVal = false;
File unusedFile = new File(unusedFilename);
File inUseFile = new File(inUseFilename);
formattedTime = new Date().toString();
String inUseText = "This file created by the Alfresco cron job to MoveFileAndCreateDir "
+ "(move files from Unfiled to Filed folders).\n"
+ "Running on " + localMachineAddress + "\n Started at " + formattedTime + "\n";
try {
FileWriter fstream = new FileWriter(inUseFile);
BufferedWriter out = new BufferedWriter(fstream);
// attempt to rename file
logMutex.debug(" Attempting to rename mutex file " + unusedFilename + " to " + inUseFilename);
if ( unusedFile.renameTo(inUseFile) ) {
logMutex.debug(" Rename to inUse successful");
out.write(inUseText);
out.flush();
out.close();
returnVal = true; // lock was acquired
} else {
// System.out.println("Rename to inUse failed");
logMutex.error(" Rename of " + unusedFilename + " to " + inUseFilename + " failed in tryAcquire().");
}
} catch ( Exception e ) {
throw new InterruptedException("Error acquiring lock in tryAcquire(): " + e.getMessage());
}
return returnVal;
}
public void release() {
File unusedFile = new File(unusedFilename);
File inUseFile = new File(inUseFilename);
String unusedText = "This file was last by the Alfresco cron job to MoveFileAndCreateDir "
+ "Ran on " + localMachineAddress + "\n Started at " + formattedTime + "\n";
try {
FileWriter fstream = new FileWriter(inUseFile);
BufferedWriter out = new BufferedWriter(fstream);
out.write(unusedText);
out.flush();
out.close();
// attempt to rename file
logMutex.debug(" Attempting to rename active mutex file " + inUseFilename + " back to " + unusedFilename);
if ( inUseFile.renameTo(unusedFile) ) {
logMutex.debug(" Rename back to unused successful");
} else {
logMutex.error(" Rename of " + inUseFilename + " to " + unusedFilename + " failed in release().");
}
} catch ( Exception e ) {
logMutex.error("Error resetting lock file in release(): " + e.getMessage());
}
} // release()
} // end of class FileRenameMutex