How to add Progress bar to File Copy in Java - java

so I have class that is used to copy all of a specific file type from one directory to another directory. This class does work, but I am curious on what would be the best method of adding a progress bar to let the users know how far along in copying all the files.
So my question is, what would be the best method of adding a progress bar to this class. As you may see, there is no GUI being made by this class as it stands.
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFilesFromType
{
public static void main(File SourcePath, File DestPath)
{
new CopyFilesFromType().copy("tif", SourcePath.toString(), DestPath.toString());
}
private FileTypeOrFolderFilter filter = null;
private void copy(final String fileType, String fromPath, String outputPath)
{
filter = new FileTypeOrFolderFilter(fileType);
File currentFolder = new File(fromPath);
File outputFolder = new File(outputPath);
scanFolder(fileType, currentFolder, outputFolder);
}
private void scanFolder(final String fileType, File currentFolder, File outputFolder)
{
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileType, file, outputFolder);
} else {
copy(file, outputFolder);
}
}
}
private void copy(File file, File outputFolder)
{
try {
System.out.println("\tCopying [" + file + "] to folder [" + outputFolder + "]...");
InputStream input = new FileInputStream(file);
OutputStream out = new FileOutputStream(new File(outputFolder + File.separator + file.getName()));
byte data[] = new byte[input.available()];
input.read(data);
out.write(data);
out.flush();
out.close();
input.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final class FileTypeOrFolderFilter implements FileFilter
{
private final String fileType;
private FileTypeOrFolderFilter(String fileType)
{
this.fileType = fileType;
}
public boolean accept(File pathname)
{
return pathname.getName().endsWith("." + fileType) || pathname.isDirectory();
}
}
}

Wrap the FileInputStream in a javax.swing.ProgressMonitorInputStream.

Related

Printing contents of an imported class to console in java

I'm programming in an online IDE (it is studio.code.org) (For a programming course). I would like to switch to a local IDE, but the online IDE uses some imports that are unavailable to download, but can be used in the code that has been written in the online IDE. This is in java. To make this a more general form of question that applies to (and will help) most people:
This is in java. I'm trying to print the contents of a file out in the console whose path is unknown, but is used as an import. Is it possible? If so, what code do I need to run to print the file out in console (from where I can copy paste it and use it elsewhere).
Here's the source code for something I tried to make this happen (but it didn't work, I'll show what output I got from the console below the code):
import java.io.*;
import org.code.neighborhood.Painter;
public class MyNeighborhood {
public static void main(String[] args) {
try {
Class<?> cls = Class.forName("org.code.neighborhood.Painter");
String fileName = cls.getName().replace('.', File.separatorChar) + ".class";
File file = new File(fileName);
System.out.println("File path: " + file.getAbsolutePath());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fis.read(buffer);
fis.close();
System.out.println(new String(buffer));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output from console:
[JAVALAB] Connecting...
[JAVALAB] Compiling...
[JAVALAB] Compilation successful.
[JAVALAB] Running...
File path: /tmp/org/code/neighborhood/Painter.class
As you may have noticed I have found a file, but it is empty, although I know that the real file that is being imported is certainly not empty.
I do have read access to the system as well since I am able to navigate the root folder by using the code below:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
boolean readContent = false; // change this to true to read file content, false to read file names
File directory = new File("/");
if (readContent) {
String fileName = "";
readFileContent(directory, fileName);
} else {
String[] fileNames = readFileNames(directory);
if (fileNames == null) {
System.out.println("Directory not found.");
} else {
System.out.println("Files in the directory:");
for (String fileName : fileNames) {
File file = new File(directory, fileName);
if (file.isDirectory()) {
System.out.println("Directory: " + fileName);
} else if (file.isFile()) {
System.out.println("File: " + fileName);
}
}
}
}
}
private static void readFileContent(File directory, String fileName) {
File file = new File(directory, fileName);
if (file.isFile()) {
try (FileReader reader = new FileReader(file)) {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
} else {
System.out.println("File not found.");
}
}
private static String[] readFileNames(File directory) {
if (directory.isDirectory()) {
return directory.list();
}
return null;
}
}

How to create a json file and its content

I am creating an Android module in react-native
I never worked with Java or writing code in Java
How can I complete the code below?
What I want
1- look and verify if the directory exist if it exist then remove it.
2- recreate the directory.
3- create a json file and add its content.
Here is what I got so far
#ReactMethod
public string write(string content) {
var folder = "NovelManager";
File path = Paths.get(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), folder);
var fullPath = Paths.get(path, "NovelManager.backup.json");
makeDir(path);
File file = new File(path, "NovelManager.backup.json");
if (!file.exists())
file = file.createNewFile();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
out.write(content);
out.close();
return file.getAbsolutePath();
}
private void makeDir(string dirPath){
var dir = new File(dirPath);
if (!dir.exists())
dir.mkdir();
}
Update and solution
After to much hard work this did thing for me.
Here is the complete code for anyone who have similar problem.
// DownloadFileModule.java
package com.novelmanager;
import android.view.View;
import android.app.Activity;
import java.io.BufferedWriter;
import java.io.Console;
import java.io.File;
import java.io.FileWriter;
import android.os.Environment;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
public class DownloadFileModule extends ReactContextBaseJavaModule {
#Override
public String getName() {
return "DownloadFileModule";
}
#ReactMethod(isBlockingSynchronousMethod = true)
public String write(String content) {
if (content == null || content == "")
return "";
try {
String folder = "NovelManager";
String fileName = "NovelManager.backup.json";
String downloadFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getPath();
String dirPath = compine(downloadFolderPath, folder);
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdir();
String path = compine(downloadFolderPath, folder, fileName);
File file = new File(path);
if (!file.exists())
file.createNewFile();
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
out.write(content);
out.close();
return file.getPath();
} catch (Exception e) {
return e.getMessage();
}
}
private String compine(String... more) {
String url = more[0];
for (int i = 1; i < more.length; i++) {
String str = more[i];
if (str.startsWith("/"))
str = str.substring(1);
if (str.endsWith("/"))
str = str.substring(0, str.length() - 1);
if (url.endsWith("/"))
url = url.substring(0, url.length() - 1);
url = url + "/" + str; // relative url
}
return url; // relative url
}
DownloadFileModule(ReactApplicationContext reactContext) {
super(reactContext);
}
}
To delete directory
public boolean deleteDirectory(Path pathToBeDeleted) throws IOException {
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
return !Files.exists(pathToBeDeleted);
}
To write to file
public void writeToFile(String content, File file) throws IOException {
Files.write(file.toPath(), content.getBytes());
}
You can use Apache FileUtils to perform all the required operations for e.g.
Reference : https://commons.apache.org/proper/commons-io/javadocs/api-2.5/index.html?org/apache/commons/io/FileUtils.html
FileUtils.cleanDirectory(path); //clean out directory (this is optional)
FileUtils.forceDelete(path); //delete directory
FileUtils.forceMkdir(path); //create directory
FileUtils.touch(file)); //create new file

Java application not completing

Was trying to get a JFrame added to see if it would help with using launch4j to convert a small jar file to an .exe. I wrote a short program to help sort HPLC data at work and want to make it just a simple point and click.
It works when I run it from the command line java KFile and the JFileChooser lets me choose directories for the script to work on. When I converted it to the .exe, the JFileChooser never rendered and the .exe closes.
I read that I might need a JFrame parent and so I created a JFrame, but now the script hangs before completion as if waiting for the frame to close. I'm pretty new to java, so I'm not sure how I to resolve this issue.
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.FileVisitResult;
import java.nio.MappedByteBuffer;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import java.util.Collection;
import java.util.ArrayList;
import java.nio.file.SimpleFileVisitor;
public class KFile extends SimpleFileVisitor<Path> {
public static void main(String[] args) {
Path currPath = Paths.get("");
String currDir = currPath.toAbsolutePath().toString();
System.out.println(currDir);
File dataDir = chooseDir("open");
File destDir = chooseDir("save");
if(!destDir.exists()) {
try {
destDir.mkdir();
}
catch (SecurityException se) {
System.out.println("Couldn't make directory!");
}
}
int n = 0;
if(dataDir.exists()) {
Collection<Path> allDir = new ArrayList<Path>();
try {
addTree(dataDir.toPath(),allDir);
}
catch (IOException e) {
System.out.println("Error with scanning");
}
for( Path thisPath : allDir ) {
if(thisPath.toString().contains("Report.pdf")) {
Path thisDir = thisPath.getParent();
File f = new File(thisDir.toString(), "\\Report.txt");
n = n + 1;
String fileName = "Report " + n + ".pdf";
try {
fileName = parseName(f);
System.out.println(fileName);
} catch (IOException e) {
e.printStackTrace();
}
File thisFile = new File(destDir + "\\" + fileName);
try {
copyFile(thisPath.toFile(),thisFile);
} catch ( IOException e) {
e.printStackTrace();
}
}
}
}
}
public static boolean copyFile(File sourceFile, File destFile) throws IOException {
//create file if it doesn't exist.
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
return true;
}
return false;
}
}
public static File chooseDir(String s) {
JFrame myFrame = new JFrame("HPLC Data Transfer");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
JFileChooser chooser = new JFileChooser();
File currDir = new File(System.getProperty("user.home") + "\\Documents");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setCurrentDirectory(currDir);
int choice = 0;
if (s.equals("save")) {
choice = chooser.showSaveDialog(myFrame);
} else {
choice = chooser.showOpenDialog(myFrame);
}
myFrame.setVisible(false);
myFrame.removeAll();
if(choice == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open: " + chooser.getSelectedFile().getName());
return chooser.getSelectedFile();
}
return new File("");
}
static String parseName(File f) throws IOException {
BufferedReader textReader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
int lnCnt = 32;
String[] fileData = new String[lnCnt];
for (int i = 0; i < lnCnt; i++) {
fileData[i] = textReader.readLine();
}
fileData[1] = fileData[1].replace("\uFEFF","");
String name = fileData[1].substring(13) + ".pdf";
textReader.close();
return name;
}
static void addTree(Path directory, final Collection<Path> all)
throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
all.add(file);
return FileVisitResult.CONTINUE;
}
});
}
}
You could try changing
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
and then call
myFrame.dispose();
to terminate the JFrame.
Since javadocs says EXIT_ON_CLOSE terminates the whole program using System.exit(); I'm not sure if that's the problem that is stopping your application but I hope it helps :)
It looks like you just called setVisible(false) when dealing with your JFrame. That just hides your JFrame, it doesn't get rid of it. If you want to get rid of your frame entirely (and all of its resources), call myFrame.dispose();

Java : InputStream to Multi-part file conversion, result file is empty

I am working on a Java application in which I am trying to create a Multipart file out of downloaded InputStream. Unfortunately, it is not working and the Multipart file is empty. I checked the size of savedFile on disk before copying it to Multipart, and it has correct size, attributes, content.
What am I doing wrong in the conversion, there is no stacktrace, as I am catching it.
Code :
// InputStream contains file data.
byte[] bytes = IOUtils.toByteArray(inputStream);
File file = new File(msg + "temp");
if (file.exists() && file.isDirectory()) {
OutputStream outputStream = new FileOutputStream(new File(msg + "temp" + "/" +
groupAttachments.getFileName()));
outputStream.write(bytes);
outputStream.close();
}
java.io.File savedFile = new java.io.File(msg + "temp" + "/" +
groupAttachments.getFileName());
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false,
savedFile.getName(), (int) savedFile.length(), savedFile.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
System.out.println("Saved file size is "+savedFile.length());
if (multipartFile.isEmpty()) {
System.out.println("Dropbox uploaded multipart file is empty");
} else {
System.out.println("Multipart file is not empty.");
}
this.dropboxTask.insertFile(multipartFile, "",
savedPersonalNoteObject.getNoteid(), (long) 0, true);
Path path = Paths.get(msg + "temp" + "/" + groupAttachments.getFileName());
Console output :
Multipart file is not empty
Bytes are not null
File path is /My Group
Input stream is not null
Saved file size is 4765
Dropbox uploaded multipart file is empty
Multipart file is empty
Bytes are not null
What am I doing wrong in the conversion? Any help would be nice. Thanks a lot.
The DiskFileItem uses a DeferredFileOutputStream which uses an in-memory byte-array that is only filled when bytes are actually transferred.
Since files are used directly and no bytes are actually copied,
the byte-array is never filled. See for yourself in the source code:
Source code CommonsMultipartFile
Source code DiskFileItem
Source code DeferredFileOutputStream
So, instead of just calling fileItem.getOutputStream();, transfer the bytes to fill the in-memory byte-array:
try (OutputStream out = fileItem.getOutputStream();
InputStream in = Files.newInputStream(file.toPath())) {
IOUtils.copy(in, dfos);
}
and then the tranferTo call will work.
This appears to be a bit cumbersome for just moving a file: CommonsMultipartFile only calls fileItem.write((File)dest) in the transferTo method.
Below are two test cases, one using the DiskFileItem and one using the LocalFileItem. The code for LocalFileItem is shown further below.
I used dependencies org.springframework:spring-web:4.2.2.RELEASE, commons-fileupload:commons-fileupload:1.3.1 and junit:junit:4.12
Test class CommonMp:
import static org.junit.Assert.*;
import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class CommonMp {
private final Charset CS = StandardCharsets.UTF_8;
#Test
public void testLocalMp() {
Path testInputFile = null, testOutputFile = null;
try {
testInputFile = prepareInputFile();
LocalFileItem lfi = new LocalFileItem(testInputFile);
CommonsMultipartFile cmf = new CommonsMultipartFile(lfi);
System.out.println("Empty: " + cmf.isEmpty());
testOutputFile = testInputFile.getParent().resolve("testMpOutput.txt");
cmf.transferTo(testOutputFile.toFile());
System.out.println("Size: " + cmf.getSize());
printOutput(testOutputFile);
} catch (Exception e) {
e.printStackTrace();
fail();
} finally {
deleteSilent(testInputFile, testOutputFile);
}
}
#Test
public void testMp() {
Path testInputFile = null, testOutputFile = null;
try {
testInputFile = prepareInputFile();
DiskFileItem di = new DiskFileItem("file", "text/plain", false, testInputFile.getFileName().toString(),
(int) Files.size(testInputFile), testInputFile.getParent().toFile());
try (OutputStream out = di.getOutputStream();
InputStream in = Files.newInputStream(testInputFile)) {
IOUtils.copy(in, out);
}
CommonsMultipartFile cmf = new CommonsMultipartFile(di);
System.out.println("Size: " + cmf.getSize());
testOutputFile = testInputFile.getParent().resolve("testMpOutput.txt");
cmf.transferTo(testOutputFile.toFile());
printOutput(testOutputFile);
} catch (Exception e) {
e.printStackTrace();
fail();
} finally {
deleteSilent(testInputFile, testOutputFile);
}
}
private Path prepareInputFile() throws IOException {
Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir"));
Path testInputFile = tmpDir.resolve("testMpinput.txt");
try (OutputStream out = Files.newOutputStream(testInputFile)){
out.write("Just a test.".getBytes(CS));
}
return testInputFile;
}
private void printOutput(Path p) throws IOException {
byte[] outBytes = Files.readAllBytes(p);
System.out.println("Output: " + new String(outBytes, CS));
}
private void deleteSilent(Path... paths) {
for (Path p : paths) {
try { if (p != null) p.toFile().delete(); } catch (Exception ignored) {}
}
}
}
The custom LocalFileItem class, YMMV!
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemHeaders;
public class LocalFileItem implements FileItem {
private static final long serialVersionUID = 2467880290855097332L;
private final Path localFile;
public LocalFileItem(Path localFile) {
this.localFile = localFile;
}
#Override
public void write(File file) throws Exception {
Files.move(localFile, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
#Override
public long getSize() {
// Spring's CommonsMultipartFile caches the file size and uses it to determine availability.
long size = -1L;
try {
size = Files.size(localFile);
} catch (IOException ignored) {}
return size;
}
#Override
public void delete() {
localFile.toFile().delete();
}
/* *** properties and unsupported methods *** */
private FileItemHeaders headers;
private String contentType;
private String fieldName;
private boolean formField;
#Override
public FileItemHeaders getHeaders() {
return headers;
}
#Override
public void setHeaders(FileItemHeaders headers) {
this.headers = headers;
}
#Override
public InputStream getInputStream() throws IOException {
throw new IOException("Only method write(File) is supported.");
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
#Override
public String getContentType() {
return contentType;
}
#Override
public String getName() {
return localFile.getFileName().toString();
}
#Override
public boolean isInMemory() {
return false;
}
#Override
public byte[] get() {
throw new RuntimeException("Only method write(File) is supported.");
}
#Override
public String getString(String encoding)
throws UnsupportedEncodingException {
throw new RuntimeException("Only method write(File) is supported.");
}
#Override
public String getString() {
throw new RuntimeException("Only method write(File) is supported.");
}
#Override
public String getFieldName() {
return fieldName;
}
#Override
public void setFieldName(String name) {
this.fieldName = name;
}
#Override
public boolean isFormField() {
return formField;
}
#Override
public void setFormField(boolean state) {
this.formField = state;
}
#Override
public OutputStream getOutputStream() throws IOException {
throw new IOException("Only method write(File) is supported.");
}
}

IndexOutOfBoundsException in File array. What could be the issue?

So I have a directory in my local C drive.
C:/Search Files/Folder [number]/hello.txt
Inside Search Files I have four foldes named:
Folder 1
Folder 2
Folder 3
Folder 4
Inside Folder 1 I have a a file called hello.txt with some String in it.
What I want to do is grab the fileDirectory, fileName and fileContent and put it in a List of XMLMessage objects. I have pasted my main class and my XMLMessage POJO. When I run it, I am getting an indexOutOfBoundsException. I have been stuck for a couple hours now. I need another pair of eyes to look into this.
Thanks,
package org.raghav.stuff;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class GetFile {
public static void main(String[] args) throws IOException {
File[] files = new File("C:\\Search Files").listFiles();
showFiles(files);
}
public static void showFiles(File[] files) throws IOException {
String line = null;
List<XMLMessage> xmlMessageList = new ArrayList<XMLMessage>();
int i = 0;
//XMLMessage folderFile = new XMLMessage();
try {
for (File file : files) {
if (file.isDirectory()) {
String fileName = file.getName();
System.out.print(fileName);
xmlMessageList.get(i).setFileName(fileName);
//folderFile.setFileName(fileName);
showFiles(file.listFiles()); // Calls same method again.
} else {
xmlMessageList.get(i).setFileDirectory(file.getName() + file.toString());
//folderFile.setFileDirectory(file.getName() + file.toString());
System.out.print("\tFile: " + file.getName()
+ file.toString());
// System.out.println("Directory: " + file.getName());
BufferedReader in = new BufferedReader(new FileReader(file));
while ((line = in.readLine()) != null) {
xmlMessageList.get(i).setFileContent(line);
// folderFile.setFileContent(line);
System.out.print("\t Content:" + line);
}
in.close();
System.out.println();
}
i++;
}
} catch (NullPointerException e) {
e.printStackTrace();
}
System.out.println(xmlMessageList.toString());
}
}
Here is the POJO:
package org.raghav.stuff;
public class XMLMessage {
private String fileDirectory;
private String fileName;
private String fileContent;
public final String FILE_NAME = "fileName";
public final String FILE_DIRECTORY = "fileDirectory";
public XMLMessage(String fileDirectory, String fileName, String fileContent) {
this.fileDirectory = fileDirectory;
this.fileName = fileName;
this.fileContent = fileContent;
}
public XMLMessage() {
}
public String getFileDirectory() {
return fileDirectory;
}
public void setFileDirectory(String fileDirectory) {
this.fileDirectory = fileDirectory;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileContent() {
return fileContent;
}
public void setFileContent(String fileContent) {
this.fileContent = fileContent;
}
public String toString(){
String returnString = "File Directory: " + fileDirectory + "\n" + "File Name" + fileName + "\n" + "File Content: " + fileContent;
return returnString;
}
/*public String createResponseFileName(String fileName){
int lastDot = fileName.lastIndexOf('.');
String responseFileName = fileName.substring(0, lastDot) + "Response" + fileName.substring(lastDot);
return responseFileName;
}*/
/*public String createResponseFileContent(String fileContent){
this.
}*/
}
You're never populating your list. I suspect you should actually have:
for (File file : files) {
XMLMessage message = new XMLMessage();
xmlMessageList.add(message);
if (file.isDirectory()) {
String fileName = file.getName();
System.out.print(fileName);
message.setFileName(fileName);
//folderFile.setFileName(fileName);
showFiles(file.listFiles()); // Calls same method again.
} else {
... etc, using message instead of xmlMessageList.get(i)
}
}
Then you don't need the i variable at all.
I think Jon Skeet is right.
you never populate your list.
you should use your constructor
XmlMessage m = new XMLMessage( fileDirectory, fileName,fileContent)
xmlMessageList.add(m);

Categories

Resources