how to display the console result in a textarea with java - java

here is a java program that allows to display the files of each directory
the problem how to display the result in a textarea
private static void
findFilesRecursively(File file, Collection<File> all, final String extension) {
final File[] children = file.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.getName().endsWith(extension) ;
}}
);
if (children != null) {
//Pour chaque fichier recupere, on appelle a nouveau la methode
for (File child : children) {
all.add(child);
findFilesRecursively(child, all, extension);
}
}
}
public static void main(String[] args)
{
//try {
final Collection<File> all = new ArrayList<File>();
// JFileChooser fc = new JFileChooser(".");
// int returnVal = fc.showOpenDialog(null);
findFilesRecursively(new File("c:\\repertoire"), all,"");
//File outputFile = new File("C:\\Users\\21365\\Desktop\\tt.txt");
//FileOutputStream fos = new FileOutputStream(outputFile);
for (int i = 0; i < all.size(); i++) {
for (File file : all) {
if(file.isDirectory()==true){
System.out.println("le repertoire \t"+file.getName()+"\t contien");
}else{

You should not iterate through your list twice - get rid of one of these 2 for loops :
for (int i = 0; i < all.size(); i++) {
for (File file : all) {
Also instead of using System.out.println(…) to print to console, just create a JFrame / JTextArea and use its append(String text) method, eg :
if (file.isDirectory() == true) {
yourTextArea.append("le repertoire \t" + file.getName() + "\t contien");
} else {
yourTextArea.append(file.getName());
}

Related

How to store list of files and folder in list or set using java?

I have return code to retrieve a list of all filepaths within a directory but I'm only getting the contents of the last folder. I have two folders, each has 3 files.
Here is my code:
import java.io.*;
import java.util.*;
class Filedirexts
{
public static void main(String[] args) throws IOException
{
String Dirpath = "E:/Share/tstlpatches";
String fieldirpath ="";
File file = new File(Dirpath);
List<String> strfilelst = new ArrayList<String>();
strfilelst = Filedirexts.getsubdir(file);
System.out.println(strfilelst.size());
for(int i=0;i<strfilelst.size();i++)
{
fieldirpath = strfilelst.get(i);
System.out.println("fieldirpath : "+fieldirpath);
}
}
public static List<String> getsubdir(File file) throws IOException
{
File[] filelist = file.listFiles();
List<String> strfileList = new ArrayList<String>();
System.out.println("filelist" + filelist.length);
for (int i=0; i< filelist.length ; i++)
{
if(filelist[i].exists())
{
if(filelist[i].isFile())
{
file = filelist[i];
System.out.println( " fileeach file : "+fileeach.getAbsolutePath());
strfileList.add(file.getAbsolutePath());
}
else if (filelist[i].isDirectory())
{
file = filelist[i];
System.out.println( " fileeach Directory : "+fileeach.getCanonicalPath());
strfileList = Filedirexts.getsubdir(file);
strfileList.add(file.getCanonicalPath().toString());
}
}
}
return strfileList;
}
}
This is my folder structure:
MainPath E:\Share\tstlpatches which is used in code itself
E:\Share\tstlpatches\BE
E:\Share\tstlpatches\BE\graphical
E:\Share\tstlpatches\BE\graphical\data1.txt
E:\Share\tstlpatches\BE\graphical\data2.txt
E:\Share\tstlpatches\BE\graphical\data3.txt
E:\Share\tstlpatches\BE\test
E:\Share\tstlpatches\BE\test\1.txt
E:\Share\tstlpatches\BE\test\2.txt
E:\Share\tstlpatches\BE\test\readme.txt
I'm only getting
E:\Share\tstlpatches\BE
E:\Share\tstlpatches\BE\test
E:\Share\tstlpatches\BE\test\1.txt
E:\Share\tstlpatches\BE\test\2.txt
E:\Share\tstlpatches\BE\test\readme.txt
If I use the normal method, it works fine, but when I use with the list I'm only getting the constents of the last folder.
What do I need to do to make the code work properly?
Your recursive method is incorrectly creating a new ArrayList<String> in each call and returning this new ArrayList in each invocation. This is why you are only seeing the contents of the last call.
Here's how to fix this:
1) Change the getsubdir to be void and pass in the List as a parameter.
public static void getsubdir(File file, List<String> strfileList) throws IOException
{
File[] filelist = file.listFiles();
System.out.println("filelist " + filelist.length);
for (int i=0; i< filelist.length ; i++)
{
if(filelist[i].exists())
{
if(filelist[i].isFile())
{
file = filelist[i];
System.out.println( " fileeach file : "+file.getAbsolutePath());
strfileList.add(file.getAbsolutePath());
}
else if (filelist[i].isDirectory())
{
file = filelist[i];
System.out.println( " fileeach Directory : "+file.getCanonicalPath());
// Note: Since you want the directory first in the list,
// add it before the recursive call
strfileList.add(file.getCanonicalPath().toString());
Filedirexts.getsubdir(file, strfileList);
}
}
}
}
2) Change the way you call it from main:
Instead of:
strfilelst = Filedirexts.getsubdir(file);
Just use:
Filedirexts.getsubdir(file, strfilelst);

How to open java,python,other files in a JEditorPane

So I was wondering how I can actively change the color of keywords in the java text pane. I understand a document listener is will have to be used, but at the moment it doesn't seem to be working, in fact putting it in the document listener leads to me not being able to properly open a file or color at all. So how can I actively call a method that changes color of keywords in java. This is the code that will search for keywords and it works when I open files, just not actively.
public void findKeyWords(String directory) throws FileNotFoundException
{
final StyleContext cont = StyleContext.getDefaultStyleContext();
final AttributeSet jKeyWord = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.RED);
final AttributeSet jOperator = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.MAGENTA);
final AttributeSet jtypes = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.CYAN);
ArrayList<String> words = loadKeyWords(directory);
for (String line : words)
{
searchJava(line,jKeyWord);
}
ArrayList<String> operators = loadOperators(directory);
for (String line : operators)
{
searchJava(line, jOperator);
}
ArrayList<String> types1 = loadTypes(directory);
for (String line : types1)
{
searchJava(line, jtypes);
}
}
private ArrayList<String> loadKeyWords(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/keywords.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(scan.next() + " ");
}
scan.close();
return javaWords;
}
private ArrayList<String> loadOperators(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/operators.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(scan.next());
}
scan.close();
return javaWords;
}
private ArrayList<String> loadTypes(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/types.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(" " + scan.next());
}
scan.close();
return javaWords;
}
public void searchJava(String wordToSearch, AttributeSet javaAttr)
{
final AttributeSet attr = javaAttr;
Document text = textArea.getDocument();
int m;
int t;
int total = 0;
for (String line : textArea.getText().split("\n"))
{
m = line.indexOf(wordToSearch);
if(m == -1)
{
if(isUnix())
{
total += line.length() + 1;
}
else if(isWindows())
{
total += line.length();
}
else if(isMac())
{
total += line.length() + 1;
}
else
{
total += line.length() + 1;
}
continue;
}
try{
text.remove(total + m, wordToSearch.length());
text.insertString(total + m, wordToSearch, attr);
}catch(BadLocationException ex)
{}
while(true)
{
m = line.indexOf(wordToSearch, m + 1 );
if (m == -1)
{
break;
}
try
{
text.remove(total + m, wordToSearch.length());
text.insertString(total + m, wordToSearch, attr);
}catch(BadLocationException e)
{
}
}
if(isUnix())
{
total += line.length() + 1;
}
else if(isWindows())
{
total += line.length();
}
else if(isMac())
{
total += line.length() + 1;
}
else
{
JOptionPane.showMessageDialog(null, "Eric You Troll" );
total += line.length() + 1;
}
}
}

increase the progressbar percentage

I've the below piece of code, where there is a progress bar that has to progressed.
public void createFiles(String srcText, String destText, JTextArea outputTextArea, JProgressBar progressBar) {
String zipFilePath = srcText;
String destDirectory = destText;
UnZip unzipper = new UnZip();
File dir = new File(zipFilePath);
File[] files = dir.listFiles();
System.out.println(files.length);
double pBarInt = (double) files.length / 100;
int count = 1;
System.out.println(count);
if (null != files) {
for (int fileIntList = 0; fileIntList < files.length; fileIntList++) {
System.out.println("coun in vlocj " + count);
String ss = files[fileIntList].toString();
if (null != ss && ss.length() > 0) {
try {
if (files[fileIntList].isDirectory())
continue;
unzipper.unzip(zipFilePath + ss.substring(ss.lastIndexOf("\\") + 1, ss.length()), destDirectory,
outputTextArea);
if ((fileIntList + 1) % pBarInt == 0) {
progressBar.setValue(count);
progressBar.update(progressBar.getGraphics());
count += 1;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
Here the value of files.length is 25.
My question is, since there are 25 files 1% of them would be 2.5%, can i increase my progress bar for every 4 files processed as 10% or can i show 2.5% whenever a file has been processed.
If files.length is greater than 100, i'm able to do it, but unable to understand for files less than 100.
please let me know how can i get this done.
Thanks
You might just have to set the maximum correctly. E.g.:
progressBar.setMaximum(files.length);
To get only the files and not the directories in the first place do:
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return !file.isDirectory();
}
});
I would write the whole bit like this:
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return !file.isDirectory();
}
});
progressBar.setMaximum(files.length);
for (int i = 0; i < files.length; i++) {
File f = files[i];
try {
unzipper.unzip(f.getAbsolutePath(), destDirectory, outputTextArea);
progressBar.setValue(i);
progressBar.update(progressBar.getGraphics());
} catch (Exception ex) {
ex.printStackTrace();
}
}
And you might want to dispatch it in a thread. See the comment on your question.
Not sure why you need this condition (fileIntList + 1) % pBarInt == 0
You should be setting the progress bar count as a percentage of the total files. Try using
progress.setValue(100);
....
int progressBarValue = count * 100/files.length;
progressBar.setValue(progressBarValue);
For accuracy use the correct files.length - ignoring directories.

How to convert multipage PDF to multipage TIFF

I am using Ghost4j to convert multipage PDFs to multipage TIFF images. I haven't found an example of how this is done.
Using below code I'm able to convert the multipage PDF to images but how do I create a single multipage TIFF image out of it?
PDFDocument lDocument = new PDFDocument();
lDocument.load(filePath);
// create renderer
SimpleRenderer lRenderer = new SimpleRenderer();
// set resolution (in DPI)
lRenderer.setResolution(300);
// render as images
List<Image> lImages = lRenderer.render(lDocument);
Iterator<Image> lImageIterator = lImages.iterator();
//how to convert the images to a single TIFF image?
While this is not exactly what you are doing I did something similar. I combined multiple images in one directory into a tiff file with separate pages. Take a look at this code and see if you can pick out what you need. Also you will need external jars/libraries for this to work they can be downloaded just google them. I hope this helps you.
public class CombineImages {
private static String directory = null;
private static String combinedImageLocation = null;
private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static int folderCount = 0;
private static int totalFolderCount = 0;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the directory path that contains the images: ");
directory = scanner.nextLine(); //initialize directory
System.out.println("Please enter a location for the new combined images to be placed: ");
combinedImageLocation = scanner.nextLine(); //initialize directory
if(!(combinedImageLocation.charAt((combinedImageLocation.length() - 1)) == '\\'))
{
combinedImageLocation += "\\";
}
if(!(directory.charAt((directory.length() - 1)) == '\\'))
{
directory += "\\";
}
scanner.close();
//directory = "C:\\Users\\sorensenb\\Desktop\\CombinePhotos\\";
//combinedImageLocation = "C:\\Users\\sorensenb\\Desktop\\NewImages\\";
File filesDirectory;
filesDirectory = new File(directory);
File[] files; //holds files in given directory
if(filesDirectory.exists())
{
files = filesDirectory.listFiles();
totalFolderCount = files.length;
folderCount = 0;
if(files != null && (files.length > 0))
{
System.out.println("Start Combining Files...");
System.out.println("Start Time: " + dateFormat.format(new Date()));
combineImages(files);
System.out.println("Finished Combining Files.");
System.out.println("Finish Time: " + dateFormat.format(new Date()));
}
}
else
{
System.out.println("Directory does not exist!");
System.exit(1);
}
}
public static void combineImages(File[] files)
{
int fileCounter = 1;
ArrayList<String> allFiles = new ArrayList<String>();
String folderBase = "";
String parentFolder = "";
String currentFileName = "";
String previousFileName = "";
File previousFile = null;
int counter = 0;
for(File file:files)
{
if(file.isDirectory())
{
folderCount++;
System.out.println("Folder " + folderCount + " out of " + totalFolderCount + " folders.");
combineImages(file.listFiles());
}
else
{
try {
folderBase = file.getParentFile().getCanonicalPath();
parentFolder = file.getParentFile().getName();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(counter == 0)
{
allFiles.add(file.getName().substring(0, file.getName().indexOf('.')));
}
else
{
currentFileName = file.getName();
previousFileName = previousFile.getName();
currentFileName = currentFileName.substring(0, currentFileName.indexOf('.'));
previousFileName = previousFileName.substring(0, previousFileName.indexOf('.'));
if(!currentFileName.equalsIgnoreCase(previousFileName))
{
allFiles.add(currentFileName);
}
}
}
previousFile = file;
counter++;
}
System.out.println("Total Files to be Combined: " + allFiles.size());
for(String currentFile:allFiles)
{
System.out.println("File " + fileCounter + " out of " + allFiles.size() + " CurrentFile: " + currentFile);
try {
createNewImage(currentFile, files, folderBase, parentFolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileCounter++;
}
}
***public static void createNewImage(String currentFile, File[] files, String folderBase, String parentFolder) throws IOException
{
//BufferedImage image;
int totalHeight = 0;
int maxWidth = 0;
int currentHeight = 0;
ArrayList<String> allFiles = new ArrayList<String>();
for(File file:files)
{
if((file.getName().substring(0, file.getName().indexOf('.'))).equalsIgnoreCase(currentFile))
{
allFiles.add(file.getName());
}
}
allFiles = sortFiles(allFiles);
BufferedImage image[] = new BufferedImage[allFiles.size()];
SeekableStream ss = null;
PlanarImage op = null;
for (int i = 0; i < allFiles.size(); i++) {
ss = new FileSeekableStream(folderBase + "\\" + allFiles.get(i));
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
op = new NullOpImage(decoder.decodeAsRenderedImage(0),
null, null, OpImage.OP_IO_BOUND);
image[i] = op.getAsBufferedImage();
}
op.dispose();
ss.close();
/*BufferedImage convertImage;
for(int i = 0; i < image.length; i++)
{
convertImage = new BufferedImage(image[i].getWidth(),image[i].getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = convertImage.getGraphics();
g.drawImage(convertImage, 0, 0, null);
g.dispose();
image[i] = convertImage;
}*/
File folderExists = new File(combinedImageLocation);
if(!folderExists.exists())
{
folderExists.mkdirs();
}
TIFFEncodeParam params = new TIFFEncodeParam();
params.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_1D);
int changeName = 1;
String tempCurrentFile = currentFile;
while((new File(combinedImageLocation + tempCurrentFile + "Combined.tif").exists()))
{
tempCurrentFile = currentFile;
tempCurrentFile += ("(" + changeName + ")");
changeName++;
}
currentFile = tempCurrentFile;
OutputStream out = new FileOutputStream(combinedImageLocation + currentFile + "Combined" + ".tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
Vector vector = new Vector();
for (int i = 1; i < allFiles.size(); i++) {
vector.add(image[i]);
}
params.setExtraImages(vector.iterator());
encoder.encode(image[0]);
for(int i = 0; i < image.length; i++)
{
image[i].flush();
}
out.close();
System.gc();
/*for(String file:allFiles)
{
image = ImageIO.read(new File(folderBase, file));
int w = image.getWidth();
int h = image.getHeight();
totalHeight += h;
if(w > maxWidth)
{
maxWidth = w;
}
image.flush();
}
BufferedImage combined = new BufferedImage((maxWidth), (totalHeight), BufferedImage.TYPE_BYTE_GRAY);
for(String file:allFiles)
{
Graphics g = combined.getGraphics();
image = ImageIO.read(new File(folderBase, file));
int h = image.getHeight();
g.drawImage(image, 0, currentHeight, null);
currentHeight += h;
image.flush();
g.dispose();
}
File folderExists = new File(combinedImageLocation + parentFolder + "\\");
if(!folderExists.exists())
{
folderExists.mkdirs();
}
ImageIO.write(combined, "TIFF", new File(combinedImageLocation, (parentFolder + "\\" + currentFile + "Combined.tif")));
combined.flush();
System.gc();*/
}***
public static ArrayList<String> sortFiles(ArrayList<String> allFiles)
{
ArrayList<String> sortedFiles = new ArrayList<String>();
ArrayList<String> numbers = new ArrayList<String>();
ArrayList<String> letters = new ArrayList<String>();
for(String currentFile:allFiles)
{
try
{
Integer.parseInt(currentFile.substring((currentFile.indexOf('.') + 1)));
numbers.add(currentFile);
}catch(Exception e)
{
letters.add(currentFile);
}
}
//String[] numbersArray = new String[numbers.size()];
//String[] lettersArray = new String[letters.size()];
for(int i = 0; i < numbers.size(); i++)
{
sortedFiles.add(numbers.get(i));
}
for(int i = 0; i < letters.size(); i++)
{
sortedFiles.add(letters.get(i));
}
return sortedFiles;
}
}

Fork/Join Example

I'm trying to use Fork/Join Mechanism ( List>> forks ) mechanism for searching all file on disk 'D:/'.
Here is the code. I got realisation of this mechanism from JLS.
public class FileFound_02 {
public static void main(String[] args) {
String searchword = null;
System.out.println("Andrey3k");
// Get Search word from arguments
if( args.length > 0 ) {
searchword = args[0];
System.out.println("____ args.length " + searchword);
}
// Get Disk Drives
File[] rootDrive = File.listRoots();
for(File sysDrive : rootDrive){
System.out.println("Drive : " + sysDrive);
System.out.println("Drive getAbsolutePath: " + sysDrive.getAbsolutePath());
// Scanning D Disk
if( sysDrive.getAbsolutePath().startsWith("D:") ) {
System.out.println("sysDrive.getAbsolutePath(): " + sysDrive.getAbsolutePath());
if( searchword != null ) {
ForkJoinPool forkJoinPool = new ForkJoinPool() ;
List<File> directories = forkJoinPool.invoke(new ScanningDirectory( new File( sysDrive.getAbsolutePath() ), searchword) );
for (int i = 0; i < directories.size(); i++) {
File file = (File) directories.get(i);
System.out.println(file.getAbsolutePath());
}
}
}
}
}
}
public class ScanningDirectory extends RecursiveTask<List<File>> {
File file;
String searchword = "";
public ScanningDirectory(File file, String searchword) {
this.file = file;
this.searchword = searchword;
}
#Override
protected List<File> compute() {
//
List<RecursiveTask<List<File>>> forks = new LinkedList<>();
List files = new ArrayList();
if (file.isDirectory()) {
for (File childFile : file.listFiles()) {
ScanningDirectory task = new ScanningDirectory(childFile, searchword);
forks.add(task);
task.fork();// запусткаем
}
for (RecursiveTask<List<File>> task : forks) {
files.addAll(task.join()); // ждем выполнения задач и результат
}
}
return files ;
}
}
Console says:
*Exception in thread "main" java.lang.NullPointerException
at andrey3k.FileFound_02.main(FileFound_02.java:40)
Caused by: java.lang.NullPointerException
at andrey3k.ScanningDirectory.compute(ScanningDirectory.java:34)
at andrey3k.ScanningDirectory.compute(ScanningDirectory.java:1)
... 7 more**
What's the problem ??? How can I fix it ???

Categories

Resources