PrintStream not creating a file? - java

I get an error at line 58 which says the file isn't found, but shouldn't the PrintStream have created the file? (Note: No file is created at all.)
Thanks!
WhyDoINeedToAddMoreDetailIAlreadySaidWhatINeedToSay
import java.io.*;
import java.util.*;
import java.text.*;
public class DownloadsFolderCleanup {
public static String directory = "C:\\Users\\User\\Downloads";
public static void main(String[] args) throws FileNotFoundException {
File[] files = (new File(directory)).listFiles();
if (files.length - 1 == 0) {
System.out.println("Downloads folder is already empty!");
}
else {
ArrayList<File> markedFiles = new ArrayList<File>();
int numInstallers = 0, numIncompleteDownloads = 0;
for (File file : files) {
String fileName = file.getName();
if (fileName.substring(fileName.length() - 4,fileName.length()).equals(".exe")) {
if (fileName.toLowerCase().contains("install") || fileName.toLowerCase().contains("setup")) {
markedFiles.add(file);
numInstallers++;
System.out.println('"' + fileName + '"' + " marked for deletion. Reason: Installer");
}
}
if (fileName.length() > 22) {
if (fileName.substring(0,11).equals("Unconfirmed") && fileName.substring(fileName.length() - 11, fileName.length()).equals(".crdownload")) {
markedFiles.add(file);
numIncompleteDownloads++;
System.out.println('"' + fileName + '"' + " marked for deletion. Reason: Incomplete download");
}
}
}
System.out.println("- - - - - - - - - - - - - - - - - - - -");
System.out.println("Total # of files scanned: " + (files.length - 1));
System.out.println("Total # of junk files found: " + markedFiles.size());
System.out.println("Installers found: " + numInstallers);
System.out.println("Incomplete download files found: " + numIncompleteDownloads);
if (markedFiles.size() == 0) {
System.out.println("No junk files were found!");
}
else {
System.out.print("Please confirm removal of all identified files. CANNOT BE UNDONE! Y/N: ");
Scanner input = new Scanner(System.in);
if (input.nextLine().equalsIgnoreCase("Y")) {
System.out.println("All marked files will be permanently deleted in 5 seconds.");
for (int c = 4; c > 0; c--) {
sleep1second();
System.out.println(c + "...");
}
sleep1second();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Date date = new Date();
PrintStream log = new PrintStream(new File(dateFormat.format(date) + " Download Folder Cleanup Log.txt"));
for (File file : markedFiles) {
System.out.println('"' + file.getName() + '"' + " deleted.");
file.delete();
log.println(file.getName());
}
log.close();
}
}
}
System.out.println();
System.out.println("Cleanup process complete!");
}
public static void sleep1second() {
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}

I'm guessing since your DateFormat "MM/dd/yyyy HH:mm" contains "/" (slashes), that path is invalid and since you're making a file at a path that contains dateFormat.format(date), the file can't be made.
In Windows the following are forbidden characters:
* . " / \ [ ] : ; | = ,

Related

Java how to read files recursive

I want to read all files recursive inside a given path and show the path and Byte size in the output of every single File.
public class ReadFilesInPathRecursion {
public void listFiles (String startDir) {
File dir = new File(startDir);
File[] files = dir.listFiles();
if (files!=null && files.length >= 0) {
for(File file : files) {
if(file.isDirectory()) {
listFiles(file.getAbsolutePath()); // Recursion (absolute)
} else {
System.out.println(file.getName() + " (size in bytes: " + file.length() + ") " + "(path: " + file.getAbsoluteFile() + ")");
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ReadFilesInPathRecursion test = new ReadFilesInPathRecursion();
String startDir = sc.next();
test.listFiles(startDir);
}

Finding all the files in my computer using JAVA

This is my code for counting all the files in my comp, the code has not stopped running and there are over 2000000 files, is this normal, or is the code in an infinite loop. THanks for all the help :)
import java.io.*;
import java.util.*;
//got the framework from this link: stackoverflow.com/questions/3154488
public class RFF {
public static void main(String [] args) {
File[] files = new File("/Users").listFiles();
showFiles(files);
System.out.println(size);
}
static File file1 = new File ("/Users/varun/Desktop/a.pdf");
static double size = file1.length();
static int i = 0;
public static void showFiles(File[] files) {
try {
for (File file: files) {
if (file.isDirectory()) {
if (file.isFile() == true)
i++;
else
i = i;
if (file.length() > size)
size = file.length();
System.out.println("FileCount: " + i + ">>> FileSize: " +file.length() + " >>> FileName: " + file.getName() );
showFiles(file.listFiles()); // Calls same method again.
} else {
i++;
if (file.length() > size)
size = file.length();
System.out.println("FileCount: " + i + ">>> FileSize: " + file.length() + " >>> FileName: " + file.getName() );
}
}
} catch (NullPointerException e) {
System.out.println ("Exception thrown :" + e);
}
}
}
It is highly likely that your users directory contains a shortcut (aka symbolic link) to a folder higher in the path, your code will follow these to get to files it has already counted this will lead to an infinite link.
E.g.
-Users
- Test
-ShortCutToUsers
See this stackoverflow question for more details of determining symbolic links:
Java 1.6 - determine symbolic links
If you're on java 7+ you can determine symbolic links as follows:
Files.isSymbolicLink(path)

Java Gui Text files Output

try {
String hour = (String) comboBox.getSelectedItem();
String filename = fileName.getText();
String date = ((JTextField)dateChooser.getDateEditor().getUiComponent()).getText();
String text = txtKeyword.getText();
String newline = "\n";
String directory = Directory.getText();
File path = new File(directory);
File[] faFiles = path.listFiles();
for(File file: faFiles){
**if(file.getName().contains(filename + "-" + date + "[" + hour + "]") == true == true || file.getName().contains(filename + "-" + date) || file.getName().contains(filename)){**
String line = null;
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
if(line.contains(text)){
jTextArea1.append(line + newline);
btnClear.setEnabled(true);
btnExport.setEnabled(true);
}
}
br.close();
}
}
}
catch(Exception e){
}
Here is my question. I'm trying to use input and loop method to search for a file. The above code works but my problem is lets say I try to find 2 different text files
1. billing-20140527[09].txt has
a)XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)XGMS,2034-05-27 30:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
2. billing-20140527[10].txt has
a)XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)HELO
**I try to find the number 1 in both text files, if lets say I input the text file name is
billing, I can find the number 1 in both text file and output them:**
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b) XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
**However, if I specify the text file name: billing-20140527[09].txt and find the number 1 inside the text file, it will only output:
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.**
Can anyone help me with this? Guide or help?
I would work with the BufferedReader. Because it reads a whole line. And then you can split the line by a delimiter (lets say a space " " ). In your case I would write a split-method which receives a String and search for the regex you want.
private void doSearch(File f2) throws IOException,
fileHandler.FileException {
File[] children = f2.listFiles();
if (children != null && searching)
for (int i = 0; i < children.length; i++) {
if (g.isReady()) {
g.setReady(false);
if (!searching) {
g.setReady(true);
break;
} else if (isDirectory(children[i])) {
g.getActualDirectoryInhalt().setText(children[i].getPath()
.substring(g.root.getText().length()));
counterDirectories++;
doSearch(children[i]);
} else if (advancedSearch && !filterSpecified(children[i])) {
raiseCounterForDirectorySize(children[i]);
continue;
} else if (checkFile(children[i])) {
counterFiles++;
searchThroughFile(children[i], this.regex);
raiseCounterForDirectorySize(children[i]);
} else {
g.getTextAreaUnreachable().setText(
g.getTextAreaUnreachable().getText() + f2
+ "\n");
raiseCounterForDirectorySize(children[i]);
}
} else {
doSearch(children[i]);
}
g.setReady(true);
}
}
And here's the other method:
public static void searchThroughFile(File f2, String regex) throws IOException,
fileHandler.FileException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(f2));
String mimeType = URLConnection.guessContentTypeFromStream(is);
ArrayList<String> linesFromFile = fileHandler.FileReaderer
.readFileIntoStringArrayList(f2);
String line = null;
if (f2.getAbsolutePath().contains(regex)) {
g.getTextAreaAdvanced()
.setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + "\n");
}
if (linesFromFile.size() != 0) {
for (int i = 0; i < linesFromFile.size(); i++) {
line = linesFromFile.get(i);
Pattern MY_Pattern = Pattern.compile(regex);
Matcher m = MY_Pattern.matcher(line);
if (!searching) {
break;
}
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
while (m.find() && searching) {
counterFoundPattern++;
g.getFoundFilesInhalt().setText(counterFoundPattern + "");
if (mimeType != null) {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + mimeType + " " + i+1 + "\n");
} else {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + i+1 + "\n");
}
}
g.setReady(true);
}
}
} catch (IOException e) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTabpane().setForegroundAt(2, Color.RED);
g.getTextAreaException().setText(
g.getTextAreaException().getText() + e + "\n");
g.setReady(true);
} catch (OutOfMemoryError oute) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTextAreaException().setText(
g.getTextAreaException().getText() + "\n"
+ "Fatal Error encured! The File will be skipped!"
+ "\n" + f2.getAbsolutePath());
g.getTabpane().setSelectedIndex(2);
g.setReady(true);
return;
}
}

File last modified time and current time

-I am not using java 8 (Date+Time API...)-I am using Java SE 7
What I am trying to accomplish here is get the last modified time of the directories inside a parent directory in miliseconds , get the current time of the system in miliseconds and then compare them (and delete if...)
This does not seem to work though..
Code:
private void deleteFolders(int sec) {
int counter = 0;
File subf[] = MyParentDirectory.listFiles();
for(File f : subf){
if(f.isDirectory()){
if((Calendar.getInstance().get(Calendar.MILLISECOND) - (f.lastModified() + 1000)) > sec){//The comparison
f.delete();
System.out.print("Deleted " + f.getName() + "\n");
counter++;
}
}
}
System.out.print("Deleted " + counter + " out of " + subf.length +" folders" + "\n");
}
It look like, there is some problem with File#lastModified() on my Windows, perhaps it is same for you. Try this:
private long getSecondsFromModification(File f) throws IOException {
Path attribPath = f.toPath();
BasicFileAttributes basicAttribs
= Files.readAttributes(attribPath, BasicFileAttributes.class);
return (System.currentTimeMillis()
- basicAttribs.lastModifiedTime().to(TimeUnit.MILLISECONDS))
/ 1000;
}
private void deleteFolders(int sec) {
int counter = 0;
File subf[] = myParentDirectory.listFiles();
for (File f : subf) {
if (f.isDirectory()) {
try {
if (getSecondsFromModification(f) > sec) {
f.delete();
System.out.print("Deleted " + f.getName() + "\n");
counter++;
}
} catch (IOException ex) {
System.out.println("Unable to access file " + f.getName() + " informtaion");
}
}
}
System.out.print("Deleted " + counter + " out of " + subf.length + " folders" + "\n");
}

Converting working code into a recursive method

Hi guys I needed to create a method to display current directory, files, subdirectories and the files of those subdirectories given a file the user has to choose. I accomplished the task and the fallowing code is printing the appropriated output. It is printing from the f.getParentFile() down, that is what want. Now I want to use recursion instead. I am trying to learn the concept of recursion. I know you need a base case and then your inductive step, but when I try to modify my code into recursive I get an infinite loop when it hits the first subdirectory. Any feedback will be appreciated.
NON-Recursive Working code
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
File[] listFiles = list[i].getAbsoluteFile().listFiles();
for (int j = 0; j < listFiles.length; j++)
{
System.out.println("\t\tSubdirectory files: " + listFiles[j].getName() + "\tsize :" + (listFiles[j].length()/1024) + "KB" );
}
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
Attempting Recursion
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
listFiles(list[i].getAbsoluteFile());
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
It is really really simple :)
public static void main(String[] args) {
filesInFolder("./");
}
public static void filesInFolder(String filename) {
File dir = new File(filename);
for (File child : dir.listFiles()) {
System.out.println(child.getAbsolutePath());
if (child.isDirectory()){
filesInFolder(child.getAbsolutePath());
}
}
}

Categories