I need help reading data from all files in a directory - java

I have a piece of code that iterates over all the files in a directory.
But I am stuck now at reading the content of the file into a String object.
public String filemethod(){
if (path.isDirectory()) {
files = path.list();
String[] ss;
for (int i = 0; i < files.length; i++) {
ss = files[i].split("\\.");
if (files[i].endsWith("txt"))
System.out.println(files[i]);
}
}
return String.valueOf(files);
}

Faced with a similar problem and wrote a code a while back. This will read the content of all files of a directory.
May require adjustments based on your file directories but its tried and tested code.Hope this helps :)
package FileHandling;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class BufferedInputStreamExample {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
public void readFile(File folder) {
ArrayList<File> myFiles = listFilesForFolder(folder);
for (File f : myFiles) {
String path = f.getAbsolutePath();
//Path of the file(Optional-You can know which file's content is being printed)
System.out.println(path);
File infile = new File(path);
try {
fis = new FileInputStream(infile);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
String line = dis.readLine();
System.out.println(line);
}
} catch (IOException e) {
} finally {
try {
fis.close();
bis.close();
dis.close();
} catch (Exception ex) {
}
}
}
}
public ArrayList<File> listFilesForFolder(final File folder){
ArrayList<File> myFiles = new ArrayList<File>();
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
myFiles.addAll(listFilesForFolder(fileEntry));
} else {
myFiles.add(fileEntry);
}
}
return myFiles;
}
}
Main method
package FileHandling;
import java.io.File;
public class Main {
public static void main(String args[]) {
//Your directory here
final File folder = new File("C:\\Users\\IB\\Documents\\NetBeansProjects\\JavaIO\\files");
BufferedInputStreamExample bse = new BufferedInputStreamExample();
bse.readFile(folder);
}
}

I would use following code:
public static Collection<File> allFilesInDirectory(File root) {
Set<File> retval = new HashSet<>();
Stack<File> todo = new Stack<>();
todo.push(root);
while (!todo.isEmpty()) {
File tmp = todo.pop();
if (tmp.isDirectory()) {
for (File child : tmp.listFiles())
todo.push(child);
} else {
if (isRelevantFile(tmp))
retval.add(tmp);
}
}
return retval;
}
All you need then is a method that defines what files are relevant for your usecase (for instance txt)
public static boolean isRelevantFile(File tmp) {
// get the extension
String ext = tmp.getName().contains(".") ? tmp.getName().substring(tmp.getName().lastIndexOf('.') + 1) : "";
return ext.equalsIgnoreCase("txt");
}
Once you have all the files, you can easily get all the text with a little hack in Scanner
public static String allText(File f){
// \\z is a virtual delimiter that marks end of file/string
return new Scanner(f).useDelimiter("\\z").next();
}
So now, using these methods you can easily extract all the text from an entire directory.
public static void main(String[] args){
File rootDir = new File(System.getProperty("user.home"));
String tmp = "";
for(File f : allFilesInDirectory(rootDir)){
tmp += allText(f);
}
System.out.println(tmp);
}

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadDataFromFiles {
static final File DIRECTORY = new File("C:\\myDirectory");
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
//append content of each file to sb
for(File f : getTextFiles(DIRECTORY)){
sb.append(readFile(f)).append("\n");
}
System.out.println(sb.toString());
}
// get all txt files from the directory
static File[] getTextFiles(File dir){
FilenameFilter textFilter = (File f, String name) -> name.toLowerCase().endsWith(".txt");
return dir.listFiles(textFilter);
}
// read the content of a file to string
static String readFile(File file) throws IOException{
return new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())), StandardCharsets.UTF_8);
}
}

Related

Zip two folders in one folder using java

I am trying to zip two folder with each having some text file. Now I want that 2 folders should zip as one folder with their respective files.
I tried to code, but there is some issue with the zip.
The Zip contains multiple folders.
Here is the code:
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFolders
{
public static void main(String[] args) throws IOException
{
List<String> listOfDir = new ArrayList<String>();
String dirpath1 = "/home/administrator/Documents/ZipTest/folder1";
String dirpath2 = "/home/administrator/Documents/ZipTest/folder2";
String ZipName = "/home/administrator/Documents/ZipTest/output.zip";
listOfDir.add(dirpath1);
listOfDir.add(dirpath2);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ZipName));
zipDirectories(listOfDir,zos);
zos.close();
System.out.println("Zip Created Successfully");
}
private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
for(String dirPath:listOfDir){
try {
zipdirectory(dirPath, zos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void zipdirectory(String dirpath, ZipOutputStream zos) throws IOException
{
File f = new File(dirpath);
String[] flist = f.list();
for(int i=0; i<flist.length; i++)
{
File ff = new File(f,flist[i]);
if(ff.isDirectory())
{
zipdirectory(ff.getPath(),zos);
continue;
}
String filepath = ff.getPath();
ZipEntry entries = new ZipEntry(filepath);
zos.putNextEntry(entries);
FileInputStream fis = new FileInputStream(ff);
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int count;
while((count = fis.read(buffer)) != -1)
{
zos.write(buffer,0,count);
}
fis.close();
}
}
}
But the output I am getting is not as expected I am getting folder 1 & folder 2
like
output.zip//home/administrator/Documents/ZipTest/ then here we are having our folder1 & folder2.
My expected output was :- inside the zip only the two folders should exist with there files.
Your zipdirectory method is used recursive here:
if(ff.isDirectory())
{
zipdirectory(ff.getPath(),zos);
continue;
}
That is creating all the folders you see.
You need to distiquish between the path of each file/dir and the path of the zip entry:
private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
for(String dirPath:listOfDir){
try {
File dir = new File(dirPath);
zipdirectory(dir, dir.getName(), zos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void zipdirectory(File dir, String dirpath,
ZipOutputStream zos) throws IOException
{
String[] flist = dir.list();
for(int i=0; i<flist.length; i++)
{
String fn = flist[i];
String fp = dirpath == null || dirpath.isEmpty()
? fn : dirpath + "/" + fn;
File ff = new File(dir, fn);
if(ff.isDirectory())
{
zipdirectory(ff, fp,zos);
continue;
}
ZipEntry entries = new ZipEntry(fp);
zos.putNextEntry(entries);
FileInputStream fis = new FileInputStream(ff);
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int count;
while((count = fis.read(buffer)) != -1)
{
zos.write(buffer,0,count);
}
fis.close();
}
}
Copy , Paste the Code and Run it for the result :-
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFolders
{
public static void main(String[] args) throws IOException
{
List<String> listOfDir = new ArrayList<String>();
String dirpath1 = "/home/administrator/Documents/ZipTest/folder1";
String dirpath2 = "/home/administrator/Documents/ZipTest/folder2";
String ZipName = "/home/administrator/Documents/ZipTest/output.zip";
listOfDir.add(dirpath1);
listOfDir.add(dirpath2);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ZipName));
zipDirectories(listOfDir,zos);
zos.close();
System.out.println("Zip Created Successfully");
}
private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
for(String dirPath:listOfDir){
try {
zipdirectory(dirPath, zos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void zipdirectory(String dirpath, ZipOutputStream zos) throws IOException
{
File f = new File(dirpath);
String[] flist = f.list();
for(int i=0; i<flist.length; i++)
{
File ff = new File(f,flist[i]);
if(ff.isDirectory())
{
zipdirectory(ff.getPath(),zos);
continue;
}
String fileName = ff.getPath().substring(ff.getPath().lastIndexOf('/'));
String folder = dirpath.substring(dirpath.lastIndexOf('/')+1);
ZipEntry entries = new ZipEntry(folder+fileName);
zos.putNextEntry(entries);
FileInputStream fis = new FileInputStream(ff);
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int count;
while((count = fis.read(buffer)) != -1)
{
zos.write(buffer,0,count);
}
fis.close();
}
}
}

How to concatenate files from an array to into a new folder? [duplicate]

This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 6 years ago.
I am trying to write a java program that will take two arguments, dirName and fileName. The program will search for all the files in dirName that end with .java and then concatenate them into a new folder called fileName. So far I have a method to search for .java files in dirName, I then put them in a file array called list but now I am struggling to iteratively add the files in this array to my new folder, fileName. Here is what I have so far:
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
public class TwoFiles {
File dir;
File name;
public TwoFiles(File dirName, File fileName) {
dir = dirName;
name = fileName;
}
public void setDir(File m) {
this.dir = m;
}
public File getDir() {
return dir;
}
public void setNewFolder(File n) {
this.name = n;
}
public File getNewFolder() {
return name;
}
public File[] Finder(File dir) {
dir = getDir();
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return name.endsWith(".java"); }
} );
}
public static void main(String[] args) {
File folder = null;
File newFolder = null;
Integer b = null;
TwoFiles tf = new TwoFiles(folder, newFolder);
folder = tf.getDir();
newFolder = tf.getNewFolder();
File[] list = tf.Finder(folder); //add to an array
//here is where I've been experimenting to add files in `list` to new folder, `fileName`.
for (File file : list)
{
FileInputStream inFile = new FileInputStream(file);
while ((b = inFile.read()) != -1)
newFolder.write(b);
inFile.close();
}
//copy files from array (list) into newFolder
}
}
Thanks for your time.
Your newFolder variable is of type File. You cannot write into this. I assume, your code does not even compile. You have to create an output stream in front of your loop:
FileOutputStream fos = new FileOutputStream( newFolder);
try
{
for (File file : list)
{
FileInputStream inFile = new FileInputStream(file);
while ((b = inFile.read()) != -1)
fos.write(b);
inFile.close();
}
}
finally
{
fos.close();
}
You can use the Apache Commons IO copyDirectory() with the IOFileFilter (for .java extensions) to copy your files from one directory to another. Before that you can ensure to create a new directory using forceMkdir() for your filename.
It's my version of your problem:
I created other constructor, where you can put only paths to directory/folder from you want concatenate files, and to file of concatenations result.
public class TwoFiles {
private File dir;
private File name;
public TwoFiles(File dirName, File fileName) {
dir = dirName;
name = fileName;
}
public TwoFiles(String dirName, String destinationFileName) throws IOException{
dir=new File(dirName);
if(!dir.isDirectory()){
throw new FileNotFoundException();//here your exception in case when dirName is file name instead folder name
}
name=new File(destinationFileName);
if(!name.exists()){
name.createNewFile();
}
}
public void setDir(File m) {
this.dir = m;
}
public File getDir() {
return dir;
}
public void setNewFolder(File n) {
this.name = n;
}
public File getNewFolder() {
return name;
}
public void concatenateFiles() throws IOException{
File[] files=dir.listFiles();
for(File file: files){
if(file.getName().endsWith(".java")){ //check is right file
prescribe(name, file);
}
}
}
/** prescribe file to new destination */
private void prescribe(File destination, File file) throws IOException {
FileInputStream inFile = new FileInputStream(file);
FileOutputStream writer=new FileOutputStream(destination, true); //true means next file will be write beginning from end of the file
int x;
while((x=inFile.read())!=-1){
writer.write(x);
}
String test="\n"; //next line in file
writer.write(test.getBytes());
writer.close();
inFile.close();
}
public static void main(String...strings){
String dirName="C/myApp/model/entity";
String fileName="C:/Users/Dell/Desktop/temp/test.java";
try {
new TwoFiles(dirName, fileName).concatenateFiles();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Include Copyright comment in header on existing and new class via eclipse formatter

I want include copyright comment on the top of every java file. I want to do it via eclipse formatter.
If it is not possible, please suggest any other way to include the copyright in existing java file.
Although it may not perfectly suit the intended approach (that is, using an eclipse plugin for that) : Once I created a small utility class that does exactly this.
It collects a list of all .java files in a given source directory. For each of the resulting files, it looks for the first line starting with the word "package". If the part above this line is not empty, then it will assume that a header is already present, and skip this file. Otherwise, it will insert a header (which is contained in some template file) before the line starting with "package".
This could arbitrarily be improved and generalized, but I only once wrote it down in order to quickly insert copyright headers into the files of an existing code base, and it worked well. Maybe you (or others) find it helpful.
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class HeaderInserter
{
public static void main(String[] args)
{
String headerTemplateFileName = "HeaderTemplate.txt";
String path = "C:/Workspace/HeaderInserter/src";
insertHeaders(path, headerTemplateFileName);
}
private static void insertHeaders(String path, String headerTemplateFileName)
{
FilenameFilter filenameFilter = new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
return name.toLowerCase().endsWith(".java");
}
};
List<String> headerLines = readLines(headerTemplateFileName);
List<File> files = listFiles(new File(path), filenameFilter);
for (File file : files)
{
System.out.println("Inserting header into "+file);
handle(file, headerLines);
}
System.out.println("Done");
}
private static void handle(File inputFile, List<String> headerLines)
{
List<String> lines = readLines(inputFile.getPath());
int index = lineIndexStartingWith(lines, "package");
if (index == -1)
{
System.err.println("No 'package' line found in "+inputFile);
return;
}
if (index > 0)
{
List<String> removedLines = lines.subList(0, index);
String removedPart = createString(removedLines);
String removedContents = removedPart.replaceAll("\n", "");
if (removedContents.trim().length() > 0)
{
System.err.println("Non-empty header found in "+inputFile);
System.err.println(removedPart);
System.err.println("Skipping");
return;
}
}
List<String> keptLines = lines.subList(index, lines.size());
List<String> writtenLines = new ArrayList<String>();
writtenLines.addAll(headerLines);
writtenLines.addAll(keptLines);
String writtenContent = createString(writtenLines);
File outputFile = new File(inputFile.getName()+"_header");
boolean written = writeContent(outputFile, writtenContent);
if (written)
{
boolean deleted = inputFile.delete();
if (!deleted)
{
System.err.println(
"Could not delete old input file: "+inputFile);
return;
}
boolean renamed = outputFile.renameTo(inputFile);
if (!renamed)
{
System.err.println("Could not rename "+outputFile);
System.err.println(" to "+inputFile);
return;
}
System.out.println("Inserted header into "+inputFile);
}
}
private static int lineIndexStartingWith(
List<String> lines, String prefix)
{
for (int i=0; i<lines.size(); i++)
{
String line = lines.get(i);
if (line.trim().startsWith(prefix))
{
return i;
}
}
return -1;
}
private static String createString(List<String> lines)
{
StringBuilder sb = new StringBuilder();
for (String line : lines)
{
sb.append(line).append("\n");
}
return sb.toString();
}
private static boolean writeContent(
File outputFile, String writtenContent)
{
try (FileWriter fw = new FileWriter(outputFile))
{
fw.write(writtenContent);
fw.close();
return true;
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
private static List<String> readLines(String fileName)
{
try
{
return Files.readAllLines(
Paths.get(fileName), Charset.defaultCharset());
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
private static List<File> listFiles(
File rootDirectory, FilenameFilter filenameFilter)
{
List<File> result = new ArrayList<File>();
listFiles(rootDirectory, filenameFilter, result);
return result;
}
private static void listFiles(
File file, FilenameFilter filenameFilter, List<File> result)
{
if (!file.isDirectory())
{
if (filenameFilter.accept(file.getParentFile(), file.getName()))
{
result.add(file);
}
}
else
{
File files[] = file.listFiles();
for (File f : files)
{
listFiles(f, filenameFilter, result);
}
}
}
}
Try Eclipse Releng Tools here
Write a script to update each file and add first line - use eclipse find and replace regex
http://java.dzone.com/articles/using-regular-expressions

Java I/O writing, mixingcase and getExtension problems

I am changing names of all files in directory and if it's text file I am changing the content but it doesn't seem to work the name of the file is changed right but content is blank/gone heres is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
public class FileOps {
public static File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
public static File[] listOfFiles = folder.listFiles();
public static void main(String[] argv) throws IOException {
toUpperCase();
}
public static void toUpperCase() throws FileNotFoundException {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String newname = mixCase(listOfFiles[i].getName());
if (listOfFiles[i].renameTo(new File(folder, newname))) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(listOfFiles[i]);
System.out.println("Done");
}
}
} else {
System.out.println("Nope");
}
}
}
public static String mixCase(String in) {
StringBuilder sb = new StringBuilder();
if (in != null) {
char[] arr = in.toCharArray();
if (arr.length > 0) {
char f = arr[0];
boolean first = Character.isUpperCase(f);
for (int i = 0; i < arr.length; i++) {
sb.append((first) ? Character.toLowerCase(arr[i])
: Character.toUpperCase(arr[i]));
first = !first;
}
}
}
return sb.toString();
}
public static void rewrite(File file) throws FileNotFoundException {
FileReader reader = new FileReader(file.getAbsolutePath());
BufferedReader inFile = new BufferedReader(reader);
try {
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
inFile.close();
outw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is several issue with your code:
Your rewrite function is perform on old name File. It should be done on the renamed File:
String newname = mixCase(listOfFiles[i].getName());
File renamedFile = new File(folder, newname);
if (listOfFiles[i].renameTo(renamedFile )) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(renamedFile);
System.out.println("Done");
}
}
you are trying to read docx and pdf file like regular text file. This cannot work. You will have to use external library like POI and pdf Box
Your rewrite function is not safe. You must unsure to close the ressources:
FileReader reader = null;
BufferedReader inFile = null;
try {
reader = new FileReader(file.getAbsolutePath());
inFile = new BufferedReader(reader);
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally
{
if(infile != null)
inFile.close();
if(reader != null)
reader .close();
}
You can't re-write a file on top of itself. you need to write the new content to a new file, then rename again.

ArrayList Menu Java

I need to make a menu that list the .txt files in a directory. For example, if i have jonsmith12.txt , lenovo123.txt , dell123.txt in the directory how would I make an arraylist menu of:
Please choose one of the following:
jonsmith12
lenovo123
dell123
Please enter your choice:
I need an arraylist menu is because I don't know how many .txt files are in the directory at any given time.
import java.io.File;
public class ListFiles
{
public static void listRecord() {
// Directory path here
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);
}
}
}
}
}
Here is the class that will display the information in the .txt file onto the console. It stills need some modifying too but I could probably figure that out.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This program reads a text file line by line and print to the console. It uses
* FileOutputStream to read the file.
*
*/
public class DisplayRec {
public static void displayRecord() throws IOException {
File file = new File("williamguo5.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So the question is: How do I implement a ArrayList menu into my ListFiles class so it will display the .txt files.
You can use the alternate method signature for File.listFiles(FilenameFilter filter) to simplify your code:
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
And unless you really enjoy writing loops, you don't even need to manually loop over the array to convert it to a List:
List<File> lstRecords = Arrays.asList(files);
Your displayRecord method was pretty close; you just needed to pass the file as an argument and use that instead of a hard-coded filename, and you needed to initialize dis.
Putting it all together:
package com.example.file;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class FileExample {
public static List<File> listRecords(File dir) {
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
return Arrays.asList(files);
}
public static void displayRecord(File file) {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
String line = dis.readLine();
while (line != null) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(line);
line = dis.readLine();
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
List<File> lstRecords = listRecords(new File("."));
for (File record : lstRecords) {
displayRecord(record);
}
}
}
It's also better to use Reader/Writer instead of InputStream/OutputStream if you're working with text files, and you should close your files in the finally block to avoid a potential resource leak.
You'll also notice I didn't explicitly use an ArrayList. In most cases, it's better to program against the interface (in this case, List) as much as possible, and only declare variables using the implementing class when you need to use a method that's only available to that class.
It looks like your sticking point above is the array. If you just need to iterate over the files in a directory, something as simple as the following will do the trick.
import java.io.File;
public class TxtEnumerator {
public static void main(String[] args) {
TxtEnumerator te = new TxtEnumerator();
te.listFiles();
}
public void listFiles() {
String filepath = "." + File.separator + "textDirectory";
File file = new File(filepath);
if (file.isDirectory()) {
for (File f : file.listFiles()) {
if (f.getName().endsWith(".txt")) {
System.out.println(f.getName());
}
}
}
}
}

Categories