Print out every text file [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I print out every text file in a particular directory with BufferedReader? Because I have a method to create file in a particular directory, and at times I want to read out every text file I've created in that directory to know what I have created.

I hope this code to help you:
// Directory path here
String path = ".";
String files;
File folder = new File(path);
// Returns an array of the files in the directory denoted.
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
//Checks if the type of the file is a text file.
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
// Reads the file and show every line on the screen.
File file = listOfFiles[i];
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
file.getAbsolutePath()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
}
}
}
}

first list all files
public File[] listf(String directoryName) {
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
System.out.println(fList);
return fList;
}
and after that pass that list into the print(File[]) function
in print function you must print each file of list

1) First Google your self for solution after that try yourself to write something and test it ... still you have any issues come to Stackoverflow to Write a question
Try this one.. Not tested but it helps you i think
BufferedReader listReader = new BufferedReader(
new FileReader("c:/File_list.dat"));
String fileName;
while((fileName = listReader.readLine()) != null) {
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
String line;
while((line = fileReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
}
listReader.close();

Do you have a list of names of the files you want to read, or do you want ever last file in a folder that is readable to be read, you say "I want to read out every text file I've created in that directory to know what I have created." so it sounds like the first one to me,
And also what kind of code have you tried already, Here are some key phrases to google.
"java get all files in a directory"
"java how to read files"
There is already a ton of info out there on these subjects
but just for a quick search on the first one I find a similar question here.

Related

How do I recursively iterate through a directory, once differentiating from a file? (Java)

So basically, I'm going to a file location, checking if its .txt. If it is then i read through that file. If it is a directory than I have to recursively and if verbose is true then I also have to output the files as i iterate through them. I am currently trying to list the files. but i keep getting "incompatible types:java.io.File[] cannot be converted to javo.io.File", but i can't think if any other way as i have to pass a file or a directory through the File parameter of collect. I'm not sure i even understand what the question is asking exactly.
Here is the question:
If file is an individual file whose name ends with the extension .txt, the method should read its contents as text one line at the time, passing each line to the previous extractIntegers method. Individual files whose name does not end with .txt should simply be ignored. If file is a directory, the method should recursively call itself for every file and directory inside that one. If the parameter verbose is set to true, the method should also output the name of each file and directory that it processes.
public static void collect(File file, Set<Integer> found, boolean verbose)
{
String fileName = file.getName();
String extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
String fileLine = "";
BufferedReader reader;
try{
reader = new BufferedReader(new FileReader(file));
if(extension.equals("txt"))
{
while((fileLine = reader.readLine()) != null)
{
extractIntegers(fileLine, found);
}
}
else if(file.isDirectory())
{
if(verbose = true)
{
System.out.println("Directory: " + file.getName());
collect(file.listFiles(), found, true);
}
else
{
collect(file.listFiles(), found, false);
}
}
}
catch(IOException e)
{
System.out.print("file/directory not found");
}
}
file.listFiles() returns an array of files. You have to pass them individually to your collect() method:
...
else if(file.isDirectory()) {
if (verbose)
System.out.println("Directory: " + file.getName());
for (File f : file.listFiles())
collect(f, found, verbose);
}
...
You are calling collect with an argument file.listFiles(), which returns an array of files. What I assume you want to do is call collect once for each file in your array of files.
Try replacing this:
collect(file.listFiles(), found, true);
with this:
for (File subFile : file.listFiles()) {
collect(file.listFiles(), found, true);
}
to do that. Make sure to replace the bad code both places it appears in your source code. Let me know if it doesn't work - I will investigate more.

AndroidStudio can't find CSV file. Tried Absolute File Path & Relative File Path

I've created a simple Android app that displays text to the user.
Now I'm attempting to implement a CSVReader to retrieve text from a CSV file. After hours of trying different things.
I finally implemented an open source CSVReader (At least it's not giving me any compile errors anymore).
Now when I run the app, it crashes and I get a "file not found" exception. Either I'm not placing my CSV file in the correct location, I'm not referencing the correct file path, or both.
I've tried using the absolute file path (ex. starting with my C:/Users/Tim/AndroidStudioProjects/...).
I've also tried using a relative path starting with the Assets folder (ex. "Assets/SOCIAL_POSTS.csv") and nothing I've tried has worked.
I've tried looking for similar Questions on Stack Overflow, and I've tried several variations of file paths and nothing has worked so far. What do you think I should try next?
Here is a link to this project on GitHub.
The code pointing to the CSV file is under
app > src > main > java > com > example > tim > inspiredquestions
The CSV file is called SOCIAL_POSTS.csv and it is under
Assets > SOCIAL_POSTS.csv
Final note: I've used StackOverflow for debugging help for a year now, but this is the first question I've asked.
Thank-you for your patience! I'm trying to be as self-reliant as I can, but I'm going on a limb and asking for help. I'm sure this problem has a simple answer I'm overlooking.
I finally figured out the answer. I added
final CSVReader csvReader = new CSVReader(new InputStreamReader(c.getAssets().open("SOCIAL_POSTS.csv") to my load function in Game.java after looking at the answer to this question. Previously I had put my CSV file in an assets folder under app/src/main but I didn't know how to access the file properly until reviewing that SO post.
How I use Android Studio for files is to position my files in the raw folder, then push them to the /data/data/yourapplication/files directory. I do this through Tools/Android/Android Device Monitor and navigate to the /data/data/yourapplication/files directory and select an icon in the upper right that says "Push a file onto the device", then navigate to the raw files in my app and select the csv file(s) I want placed in the /files directory.
From that point I aim my stream readers at that directory,
in my case, /data/data/app/com.android/example/darrell/MenuPlanner/files Directory. Files addressed here use the file extension and do not need the path specified:
public List<EntreeData> ReadEntreesFromFilesDir(Context inContext) {
this.mContext = inContext;
List<String> lines = new ArrayList<String>();
String[] separated;
try {
FileInputStream fis = mContext.openFileInput("entrees.csv");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
while ((mLine = bufferedReader.readLine()) != null) {
if (mLine == null) break;
lines.add(mLine);
}
fis.close();
isr.close();
} catch (FileNotFoundException e) {
Log.d("FILE ERROR", e.getMessage() + " not found");
} catch (IOException ioe) {
Log.d("FILE ERROR", ioe.getMessage());
}
for (int x = 0;x<lines.size();x++){
separated = lines.get(x).split(",");
EntreeData thisEntree = new EntreeData();
thisEntree.setEntreeName(separated[0].trim());
thisEntree.setCategory(separated[1].trim());
thisEntree.setSubcategory(separated[2].trim());
thisEntree.setRecipe(separated[3].trim());
mEntreeList.add(thisEntree);
}
return mEntreeList;
}
As a fallback I read from /res/raw directory which is not writeable and I am assured of file integrety. Files here do not use an extension, so point your stream reader at a file without using the extension name.
Also use the asset manager to access these files:
public List<EntreeData> ReadEntreesFileFromRaw(Context inContext) {
this.mContext = inContext;
List<String> lines = new ArrayList<String>();
String[] separated;
AssetManager assetManager = mContext.getAssets();
try {
InputStream inputStream = mContext.getResources().openRawResource(R.raw.entrees);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
int lineCount = 0;
while ((mLine = reader.readLine()) != null) {
separated = mLine.split(",");
EntreeData entreeEntry = new EntreeData();
if (mLine == null) break;
separated = mLine.split(",");
entreeEntry.setEntreeName(separated[0].trim());
entreeEntry.setCategory(separated[1].trim());
entreeEntry.setSubcategory(separated[2].trim());
entreeEntry.setRecipe(separated[3].trim());
mEntreeList.add(lineCount, entreeEntry);
lineCount++;
}
inputStream.close();
} catch (FileNotFoundException e) {
Log.d("FILE ERROR", e.getMessage() + " not found");
} catch (IOException ioe) {
Log.d("FILE ERROR", ioe.getMessage());
}
return mEntreeList;
}
Good luck and happy programming!

Java, automatic reading file from a directory [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to know if it's possible to do this:
i've some .txt file in a directory in my filesystem
i would like to write a java code that does this:
Automatically read all the files in the directory
Give me a output
Exists some library? or it's just a code problem?
It's possible?
Thanks
Reads & prints the content
public static void main(String[] args) {
List<String> li=new TestClass().textFiles("your Directory");
for(String s:li){
try(BufferedReader br = new BufferedReader(new FileReader(s))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} catch (IOException e) {
e.printStackTrace();
}
}
}
For getting all Text files in the Directory
List<String> textFiles(String directory) {
List<String> textFiles = new ArrayList<String>();
File dir = new File(directory);
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.add(file.getPath());
}
}
return textFiles;
}
Of course it's possible. You need to look at File, Reader classes. A useful method is File#listFiles. Happy coding.

java function to read a folder of files

I have a program that currently reads in a file, looks for keywords, and outputs the number of occurrences of the keywords. I need to write a function that reads in all the files and I need to insert this function in a spot so that the total number of occurrences is displayed.
I am currently reading in 1 file like this
try (BufferedReader br = new BufferedReader(new FileReader("C:\\P4logs\\out.log.2012-12-26")))
{
You will want to get your folder path and then loop through all the files in that folder and have a check that filters out files you don't want.
File path = new File(path); //path to your folder. eg. C:\\P4logs
for(File f: path.listFiles()) { // this loops through all the files + directories
if(f.isFile()) { // checks if it is a file, not a directory.
// most basic check. more checks will have to be added if
// you have other files you don't want read. (like non log files)
try (BufferedReader br = new BufferedReader(new FileReader(f.getAbsolutePath()))) {
// gets the full path of a file. so "C:\\P4logs\\out.log.2012-12-26"
//do stuff
}
}
}
It's simple:
File folder = new File("C:/path_to_your_folder/");
for (File file : folder.listFiles()) {
// Got a file. Do what you want.
}
You need a recursive function for a recursive search
void readAllFiles(final File myFile) {
if(file.isFile()) {
//read the file and whatever
return;
}
for(final File childFile : myFile.listFiles()) {
readAllFiles(childFile);
}
}

Are these two ways of creating files, the same?

I was writing a program in Java to search for a piece of text
I took these 3 as inputs
The directory, from where the search should start
The text to be searched for
Should the search must be recursive (to or not to include the directories inside a directory)
Here is my code
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File file = new File(dirToSearch);
String[] fileNames = file.list();
for(int j=0; j<fileNames.length; j++)
{
File anotherFile = new File(fileNames[j]);
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
When recursion is set true, the program returns a FILENOTFOUNDEXCEPTION
So, I referred to the site from where I got the idea to implement this program and edited my program a bit. This is how it goes
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File[] files = new File(dirToSearch).listFiles();
for(int j=0; j<files.length; j++)
{
File anotherFile = files[j];
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
It worked perfectly then. The only difference between the two snippets is the way of creating the files, but they look the same to me!!
Can anyone point me out where I messed up?
In the second example it is used listFiles() whichs returns files. In your example it is used list() which returns only the names of the files - here the error.
The problem in the first example is in the fact that file.list() returns an array of file NAMES, not paths. If you want to fix it, simply pass file as an argument when creating the file, so that it's used as the parent file:
File anotherFile = new File(file, fileNames[j]);
Now it assumes that anotherFile is in the directory represented by file, which should work.
You need to include the base directory when you build the File object as #fivedigit points out.
File dir = new File(dirToSearch);
for(String fileName : file.list()) {
File anotherDirAndFile = new File(dir, fileName);
I would close your files when you are finished and I would avoid using throws Exception.

Categories

Resources