Not deleting the Files that are accepting the condition (Recursion) - java

What is wrong with this code, I want to read all the files recursively on a folder to check if they contain a specific word and to check if they are write writable if they accept this condition I want to delete them.
public void del(String text) throws IOException {
if (UtilityClass.isEmpty(text)) {
throw new IOException("Teksti null");
}
int count = del(folder, text);
try (FileWriter fw = new FileWriter("C://Users//Admin//Desktop//deletewriteout")) {
fw.write(
"Ne totalin u fshine : " + count + " file-a te cilet ishin te shkrushem dhe qe permabin : " + text);
fw.flush();
}
}
private int del(File file, String text) throws IOException {
int counter = 0;
String line = null;
File[] fajllat = file.listFiles((File f) -> f.isFile() && f.canRead());
for (File f : fajllat) {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains(text)) {
f.delete();
counter++;
}
else if (f.isDirectory()) {
counter += del(f, text);
}
}
}
return counter;
}

You need to close the input stream before deleting the file.
private int del(File file, String text) throws IOException {
int counter = 0;
String line = null;
File[] fajllat = file.listFiles((File f) -> f.isFile() && f.canRead());
for (File f : fajllat) {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains(text)) {
// => Added
br.close();// We need to close read stream before delete
f.delete();
counter++;
}
else if (f.isDirectory()) {
counter += del(f, text);
}
}
}
return counter;
}
See here.

Related

Creating folder from text

I am getting
newDir D:\template_export\template\attachments\processed\enumeration\blocker.gif\enumeration\critical.gif\enumeration\high.gif\enumeration\low.gif\enumeration\major.gif\enumeration\medium.gif\enumeration\minor.gif\enumeration\normal.gif\enumeration\unassigned.gif\enumeration\unassigned2.gif\workflow\close.gif\workflow\defer.gif\workflow\duplicate.gif\workflow\inprogress.gif\workflow\new.gif\workflow\open.gif\workflow\reject.gif\workflow\remind.gif\workflow\reopen.gif\workflow\resolve.gif\workflow\unconfigure.gif\workflow\unresolve.gif\workflow\verify.gif\workflow\wontdo.gif\workflow\works.gif\workitemtype\bug.gif\workitemtype\enhancement.gif\workitemtype\general.gif\workitemtype\task.gif\workitemtype
new directory false
reached
java.nio.file.NoSuchFileException: D:\template_export\template\attachments\1.gif -> D:\template_export\template\attachments\processed\enumeration\blocker.gif\enumeration\critical.gif\enumeration\high.gif\enumeration\low.gif\enumeration\major.gif\enumeration\medium.gif\enumeration\minor.gif\enumeration\normal.gif\enumeration\unassigned.gif\enumeration\unassigned2.gif\workflow\close.gif\workflow\defer.gif\workflow\duplicate.gif\workflow\inprogress.gif\workflow\new.gif\workflow\open.gif\workflow\reject.gif\workflow\remind.gif\workflow\reopen.gif\workflow\resolve.gif\workflow\unconfigure.gif\workflow\unresolve.gif\workflow\verify.gif\workflow\wontdo.gif\workflow\works.gif\workitemtype\bug.gif\workitemtype\enhancement.gif\workitemtype\general.gif\workitemtype\task.gif\workitemtype\unknown.gifprocess_template_license.htmltemplate.messagestemplate_en_US.messages
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileCopy.move(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.move(Unknown Source)
at java.nio.file.Files.move(Unknown Source)
at Test.main(Test.java:60)
Error.
My code is :
public class Test {
public static void main(String[] args) {
File orgDirectory = new File("D://template_export/template/attachments"); // replace this filename
// with the path to the folder
// that contains the original images
String fileContent = "";
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachments.txt")))) {
for (String line;
(line = br.readLine()) != null;) {
fileContent += line;
}
} catch (Exception e) {
e.printStackTrace();
}
String[] newLocations = fileContent.split(",");
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
File destinationFolder = new File("D://template_export/template/attachments/processed");
if (!destinationFolder.exists()) {
System.out.println("here" + destinationFolder.mkdir());
}
int max = Math.min(orgFiles.length, newLocations.length);
for (int i = 0; i < max; i++) {
String newLocation = newLocations[i];
int lastIndex = newLocation.lastIndexOf("/");
if (lastIndex == -1) {
continue;
}
String newDirName = newLocation.substring(0, lastIndex);
System.out.println("newDirName " + newDirName);
String newName = newLocation.substring(lastIndex);
System.out.println("newName " + newName);
File newDir = new File(destinationFolder, newDirName);
System.out.println("newDir " + newDir);
if (!newDir.exists()) {
System.out.println("new directory " + newDir.mkdir());
}
try {
System.out.println("reached");
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You're concatenating all the lines of the attachments.txt file into a single destination string. Judging from the exception message, it appears that the attachments file does not contain commas at the end of each line. Thus you end up with a destination consisting of a single file name, seemingly in a deeply nested directory.
Instead, I suggest that you read the lines in one at a time into an ArrayList<String>, rather than concatenating and later splitting the destinations.
ArrayList<String> newLocations = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachments.txt")))) {
for (String line; (line = br.readLine()) != null;) {
newLocations.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Then you can use newLocations.size() where you now use newLocations.length and use newLocations.get(i) where you use newLocations[i].
EDIT: As #griFlo points out in a comment, a simpler alternative to reading the file into a list of lines is:
List<String> newLocations = Files.readAllLines(Paths.get("attachments.txt"));
If the file will not read properly with UTF-8 decoding (which is what the above call will use), or if you're compiling with Java 7, you'll have to use the two-argument version of readAllLines():
List<String> newLocations = Files.readAllLines(Paths.get("attachments.txt"),
StandardCharsets.US_ASCII); // or whatever encoding is appropriate

iterating through a list of files to check how many lines are there inside

I have been trying to write a simple code where i can go through a list of filenames, go through each file name, and calculate how many lines are there in each file.
However the code below doesn't seem to work at all (keeps initiating the debug perspective in eclipse).
public class fileScanner {
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<String>();
//add files
list.add("C:\\Users\\HuiHui\\Documents\\eclipse\\test.txt");
for (String l : list){
fileScan(l);
}
}
public static int fileScan(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean endsWithoutNewLine = false;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
endsWithoutNewLine = (c[readChars - 1] != '\n');
}
if(endsWithoutNewLine) {
++count;
}
return count;
} finally {
is.close();
}
}
}
Can anyone shed some light on this?
Is there a reason why you're using InputStream and created a BufferedInputStream instead of using BufferedReader which does the job for you ?
try this for your filescan method
int filescan(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
int count=0;
String s;
while((s=br.nextLine()) != null)
count++;
br.close();
return count;
}
Try LineNumberReader:
public static int fileScan(String filename) throws IOException {
File file = new File(filename);
LineNumberReader lnr = null;
try {
lnr = new LineNumberReader(new FileReader(file));
lnr.skip(file.length());//go to end of file
return lnr.getLineNumber();
} finally {
if(null != lnr) {
lnr.close();
}
}
}
You could use a Scanner to iterate through each file, and then increment an integer for every line that there is.
Example:
while(scanner.hasNextLine()) {
scanner.nextLine();
integer++;
}

How to extract starting of a String in Java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.
There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.
RecordType=0(MOC)
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
String line = "";
String line2 = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// extract logic starts here
if (line.startsWith("ISDN") == true) {
System.out.println("hello");
returnValue += line + "\n";
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}
We will assume that you use Java 7, since this is 2014.
Here is a method which will return a List<String> where each element is an ISDN:
private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");
// ...
public List<String> getISDNsFromFile(final String fileName)
throws IOException
{
final Path path = Paths.get(fileName);
final List<String> ret = new ArrayList<>();
Matcher m;
String line;
try (
final BufferedReader reader
= Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
m = ISDN.matcher(line);
if (m.matches())
ret.add(m.group(1));
}
}
return ret;
}

delete text file java doesn't work

Here's example:
public static void main (String[] args){
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
String temppath = "C:\\Users\\Charbel\\Desktop\\temp.txt";
File file = new File(path);
File tempfile = new File(temppath);
int numl = search("x");
int countL = 0;
String line;
try {
BufferedReader bf = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(temppath));
while (( line = bf.readLine()) != null)
{
if(countL != numl){
bw.write(line);
bw.newLine();
}
countL++;
}
bf.close();
bw.close();
file.delete();
boolean successful = tempfile.renameTo(file);
System.out.println(successful);
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
public static int search(String name)
{
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
int countL = 0;
String line;
try {
BufferedReader bf = new BufferedReader(new FileReader(path));
while (( line = bf.readLine()) != null)
{
int indexfound = line.indexOf(name);
if (indexfound == 0) {
return countL;
}
countL++;
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
return -1;
}
}
Hello there .. i am trying to read the line of a specific string in a text file , get the number of its line , then copy all the data in the file to another text file except the line of the string
the code is sometimes working 100% and sometimes no ; I go to my desktop I see both files the temp and the original one without deleting and renaming it
i think i have a problem in deleting the file what do you think coders ?
Because when the search method find name(actually "x"),don't reach the line bf.close(), so bf is still opened and file.delete() fails.
So, you need to modify the search method to the below:
public static int search(String name) {
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
int countL = 0;
String line;
BufferedReader bf = null;
try {
bf = new BufferedReader(new FileReader(path));
while (( line = bf.readLine()) != null)
{
int indexfound = line.indexOf(name);
if (indexfound == 0) {
return countL;
}
countL++;
}
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
finally {
if(bf != null) {
try {
bf.close();
}
catch(IOException ignored) {}
}
}
return -1;
}

How to find circular dependency of a string using Java

If I have 2 files say ABCD.txt and DEF.txt. I need to check if the String "ABCD" is present in DEF.txt and also the string "DEF" present in ABCD.txt and write the combination to a file.
Totally I have around 15000 files and each file contain nearly 50 - 3000 lines has to be searched. I wrote a piece of code, its working.. but it takes one hour to display the entire list...
Is any better way of performing this? Please suggest me.
public void findCyclicDependency(){
Hashtable<String, String> htFileNameList_1 = new Hashtable<String, String>();
Hashtable<String, String> htCyclicNameList = new Hashtable<String, String>();
FileWriter fwCyclicDepen = null;
PrintWriter outFile = null;
FileInputStream fstream = null;
FileInputStream fstream_1 = null;
DataInputStream in = null;
BufferedReader br = null;
DataInputStream in_1 = null;
BufferedReader br_1 = null;
String strSV_File_CK="";
boolean bFound = false;
File fileToSearch = null;
String strSVFileNameForComparison = "";
String strSVDependencyFileLine = "";
String strSVDFileLineExisting = "";
String strCyclicDependencyOut = "";
try {
File baseInputDirectory = new File(strInputPath);
List<File> baseInputDirListing = FileListing.getFileListing(baseInputDirectory);
// Printing out the filenames for the SodaSystem
for (File swPackage : baseInputDirListing)
{
if (swPackage.isDirectory() && swPackage.getName().endsWith("Plus")) {
List<File> currSwPackageFileListing = FileListing.getFileListing(swPackage);
System.out.println("\n swPackage File --> " + swPackage.getName() );
strCyclicDependencyOut = strOutputPath + "_"+ swPackage.getName() + "_CyclicDependency.xml";
System.out.println("\n strCyclicDependencyOut File --> " + strCyclicDependencyOut );
fwCyclicDepen = new FileWriter(strCyclicDependencyOut);
outFile = new PrintWriter(new BufferedWriter(fwCyclicDepen));
outFile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
outFile.write("<CyclicDependencyFile>");
for (File DependentFile : currSwPackageFileListing) {
strSV_File_CK = DependentFile.getName().substring(0, (DependentFile.getName().length() - 4)).trim();
htFileNameList_1.put(strSV_File_CK.toUpperCase(),strSV_File_CK.toUpperCase());
}
for (File DependentFile : currSwPackageFileListing)
{
fstream = new FileInputStream(DependentFile);
// Get the object of DataInputStream
in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in));
strSVFileNameForComparison = DependentFile.getName().substring(0, (DependentFile.getName().length() - 4)).trim();
//Read File Line By Line
while ((strSVDependencyFileLine = br.readLine()) != null)
{
bFound = false;
if (strSVDependencyFileLine.toUpperCase().indexOf("INDICES") == -1)
{
//Check the current line matches any of the file name in software package folder
if (htFileNameList_1.contains(strSVDependencyFileLine.trim().toUpperCase())
&& strSVDependencyFileLine.compareTo(strSVFileNameForComparison) != 0)
{
bFound = true;
// Get the file to search
for (File searchFile : currSwPackageFileListing)
{
if((searchFile.getName().substring(0, (searchFile.getName().length() - 4)).trim()).equals(strSVDependencyFileLine))
{
fileToSearch = searchFile;
break;
}
}
// Read the file where the file name is found
fstream_1 = new FileInputStream(fileToSearch);
in_1 = new DataInputStream(fstream_1);
br_1 = new BufferedReader(new InputStreamReader(in_1));
while ((strSVDFileLineExisting = br_1.readLine()) != null)
{
if (strSVDFileLineExisting.toUpperCase().indexOf("EXTRA") == -1)
{
if (htFileNameList_1.contains(strSVDFileLineExisting.trim().toUpperCase()) && bFound
&& strSVDFileLineExisting.compareTo(strSVDependencyFileLine) != 0
&& strSVDFileLineExisting.compareTo(strSVFileNameForComparison) == 0 )
{
if(!htCyclicNameList.containsKey(strSVDependencyFileLine) &&
!htCyclicNameList.containsValue(strSVDFileLineExisting))
{
htCyclicNameList.put(strSVDFileLineExisting,strSVDependencyFileLine);
outFile.write("<CyclicDepedency FileName = \"" + strSVDFileLineExisting + "\""+ " CyclicFileName = \"" +
strSVDependencyFileLine + "\" />");
break;
}
}
}
}
}
}
else
{
bFound = false;
}
}//if current line <>
}// reach each line in the current file
outFile.write("</CyclicDependencyFile>");
}
outFile.flush();
outFile.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}
Thanks
Ramm
There are several problems with your design. The most important one is repeated scanning of the file system. Try the code below.
static public void findCyclicDependency2() {
PrintWriter outFile = null;
Map<String,File> fileNames = new HashMap<String,File>();
Map<String,Set<String>> fileBackward = new HashMap<String,Set<String>>();
Map<String,Set<String>> fileForward = new HashMap<String,Set<String>>();
try {
File baseInputDirectory = new File(strInputPath);
List<File> baseInputDirListing = getFileListing(baseInputDirectory);
// Printing out the filenames for the SodaSystem
for(File swPackage:baseInputDirListing) {
if (! (swPackage.isDirectory()
|| swPackage.getName().endsWith("Plus"))) continue;
System.out.println("Loading file names");
List<File> currSwPackageFileListing = getFileListing(swPackage);
for(File dependentFile:currSwPackageFileListing) {
String name = trimName(dependentFile);
fileNames.put(name,dependentFile);
BufferedReader br = new BufferedReader(new FileReader(dependentFile));
String line;
Set<String> contFor = new HashSet<String>();
Set<String> contBack = new HashSet<String>();
while( (line=br.readLine()) != null ) {
line = line.toUpperCase().trim();
if( line.equals("EXTRA") ) continue;
if( line.equals("INDICES") ) continue;
if( line.equals(name) ) continue;
if( line.compareTo(name) == 1 ) {
contFor.add(line);
} else {
contBack.add(line);
}
}
fileBackward.put(name,contBack);
fileForward.put(name,contFor);
}
String strCyclicDependencyOut = strOutputPath + "_"
+ swPackage.getName() + "_CyclicDependency.xml";
outFile = new PrintWriter(new BufferedWriter(new FileWriter(strCyclicDependencyOut)));
outFile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
outFile.write("<CyclicDependencyFile>");
for(Entry<String,Set<String>> entry : fileForward.entrySet()) {
String curr = entry.getKey();
for(String other : entry.getValue()) {
Set<String> otherRefs = fileBackward.get(other);
if( otherRefs == null ) continue;
if( otherRefs.contains(curr) ) {
outFile.write("<CyclicDepedency FileName = \""
+ fileNames.get(curr).getPath()
+ "\""
+ " CyclicFileName = \""
+ fileNames.get(other).getPath()
+ "\" />");
}
}
}
outFile.write("</CyclicDependencyFile>");
outFile.flush();
outFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Lucene comes to my mind.
Maybe it's more efficient to index all files, then query for the file names and use the results to detect your circular dependencies.

Categories

Resources