File file = new File("C:/mydirectory/");
File[] files = file.listFiles();
for(File f: files){
System.out.println(f.getName());
f.getName() contains the name of the file but how can I open the file using f.getName() ;? Or please help me to open all the txt files using a loop.
if (f.getName().contains("name wanted")) {
FileInputStream fis = null;
try (fis = new FileInputStream(f);
// use the file input stream to read data
}
or to read lines from the file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
}
To display the name of all files you can use recursion, to get contents see above
public void display(File f) {
File[] files = file.listFiles();
for(File f: files){
if (f.isDirectory()) {
display(f);
} else if (f.getName().contains("value")) {
System.out.println(f.getName());
}
}
and call this as display(new File("C:/mydirectory/")) from a main method.
you can 'display' your result using JOptionPane
File file = new File("C:/mydirectory/");
String result = "";
for (String fileName: file.listFiles()){
result = result+"\n";
}
JOptionPane.showMessageDialog(null, result);
JOptionPanegrants static access, so you won't need any instances, the first parameter is the parent frame, null is allowed. The second parameter is the message (here: a list of all files within C:/mydirectory/) you want to 'display' ...
For read the whole file to List<String> use Files.readAllLines(f.toPath()) or Files.newInputStream(f.toPath()) for opening stream.
Related
I am getting this error in my code when trying to read a file saved on the external storage of my phone :
java.io.FileNotFoundException: shopping.txt: open failed: ENOENT (No such file or directory)
I can manage to write data to this file with success, what I did a lot of times.
However, I cannot access for reading this same file, giving the entire path or through another method.
The code writing and saving successfully :
File path = new File(this.getFilesDir().getPath());
String value = "vegetables";
// File output = new File(path + File.separator + fileName);
File output = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
// Toast.makeText(getBaseContext(), "File saved successfully!",
// Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,String.valueOf(output),Toast.LENGTH_LONG).show();
Log.d("MainActivity", "Chemin fichier = [" + output + "]");
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The writing piece of code crashing my app :
try
{
File gFile;
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
//FileInputStream fis = openFileInput("/storage/emulated/0/Android/data/com.example.namour.shoppinglist/files/shopping.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null, input="";
while ((line = reader.readLine()) != null)
input += line;
Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
reader.close();
fis.close();
Toast.makeText(MainActivity.this,"Read successful",Toast.LENGTH_LONG).show();
//return input;
}
catch (IOException e)
{
Log.e("Exception", "File read failed: " + e.toString());
//toast("Error loading file: " + ex.getLocalizedMessage());
}
What am I doing wrong ?
For sure, not a problem of permissions, since I can write with success.
Many thanks for your help.
You missed to specifiy the correct path. You are looking for a file named shopping.txt in your current working directory (at runtime).
Create a new File object with the correct path and it will work:
File input = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");. You could reuse your object from writing.
While opening the file, you are simply using new File("shopping.txt").
You need to specify the parent folder, like this:
new File(getExternalFilesDir(),"shopping.txt");
I recommend you make sure of org.apache.commons.io for IO, their FileUtils and FileNameUtils libs are great. ie: FileUtils.writeStringToFile(new File(path), data); Add this to gradle if you wish to use it: implementation 'org.apache.commons:commons-collections4:4.1'
In regards to your problem. When you write your file you are using:
getApplicationContext().getExternalFilesDir(null),"shopping.txt"
But when reading your file you are using:
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
Notice that you didn't specify a path to shopping.txt simply the file name.
Why not do something like this instead:
//Get path to directory of your choice
public String GetStorageDirectoryPath()
{
String envPath = Environment.getExternalStorageDirectory().toString();
String path = FilenameUtils.concat(envPath, "WhateverDirYouWish");
return path;
}
//Concat filename with path
public String GetFilenameFullPath(String fileName){
return FilenameUtils.concat(GetStorageDirectoryPath(), fileName);
}
//Write
String fullFilePath = GetFilenameFullPath("shopping.txt");
FileUtils.writeStringToFile(new File(fullFilePath ), data);
//Read
File file = new File(fullFilePath);
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null){
text.append(line);
if(newLine)
text.append(System.getProperty("line.separator"));
}
br.close();
I put two files in a directory and tested to see if my code can search through the files and find a match, but the FileReader won't read the second file. Here is my code and my console entry. I have narrowed the error down to the FileReader, but I don't know how to fix that.
public class Main
{
public static void searchEngine(String dir, String Search)
{
File folder = new File(dir);
String[] files = folder.list();
Integer f1 = 0;
FileReader fileReader;
ArrayList linematches;
BufferedReader bufferedReader;
Integer q;
String line;
Integer linenum;
System.out.println("Found Files:");
for (String file : files) {
System.out.println(file);
}
try {
for (String file : files) {
linematches = new ArrayList();
fileReader = new FileReader(files[f1]);
bufferedReader = new BufferedReader(fileReader);
linenum = 0;
while ((line = bufferedReader.readLine()) != null) {
linenum += 1;
if (line.contains(Search)) {
linematches.add(linenum);
}
}
q = 0;
for (int i = 0; i < linematches.size(); i++) {
System.out.println("File: " + file + " Line: " + linematches.get(i));
}
linematches.removeAll(linematches);
// Always close files.
bufferedReader.close();
f1++;
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + dir + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + dir + "'");
}
}
public static void main(String[] args)
{
while (true) {
System.out.println("Enter the search term: ");
Scanner scanner = new Scanner(System.in);
String searchterm = scanner.nextLine();
System.out.println("Enter each file location: ");
String f1 = scanner.nextLine();
searchEngine(f1, searchterm);
}
}
}
Here is the output of my console:
Enter the search term:
bla
Enter each file location:
test dir
Found Files:
testfile.txt
testfile2.txt
Unable to open file 'test dir'
The entire stack trace of the error is:
Unable to open file 'testfile2.txt' java.io.FileNotFoundException:
testfile2.txt (No such file or directory) Enter the search term: at
java.io.FileInputStream.open0(Native Method) at
java.io.FileInputStream.open(FileInputStream.java:195) at
java.io.FileInputStream.(FileInputStream.java:138) at
java.io.FileInputStream.(FileInputStream.java:93) at
java.io.FileReader.(FileReader.java:58) at
com.mangodev.Main.searchEngine(Main.java:32) at
com.mangodev.Main.main(Main.java:70)
Please help. Thank you.
It looks to me as if you have the following folder structure:
Main.class
Main.java
test dir
|-- testfile.txt
|-- testfile2.txt
You run the code from the directory containing Main.class, Main.java and test dir. Your code then lists files in the directory test dir, finding the two text files it contains, but then attempts to open them from the current directory. This is the parent directory, and of course, this isn't where those files are. They are in the sub-directory test dir. A FileNotFoundException is therefore to be expected: you're attempting to open a file in the wrong directory.
If the FileReader happens to fail on the second of the two files, does there happen to be a file testfile.txt in the parent directory as well? Your code may well have been opening this file first time through the loop instead of the one in test dir that you thought it was.
To open files within the test dir subdirectory, replace the line
fileReader = new FileReader(files[f1]);
with
fileReader = new FileReader(new File(dir, files[f1]));
In your first line in the searchEngine method you create a variable folder that contains the files in the directory. I suggest using this variable directly in your for loop instead of string filenames.
for (File file : folder.listFiles()) {
linematches = new ArrayList();
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
//rest of code...
}
I am sorry I dont have a code, I say in a few answers how to make a file and write to it, but I have another question.
I give a path to a folder in my compilation, and I want for each file that ends with a .jack to create the same file name that ends with .xml
and open the xml file and write to it.
exemple:
start.jack
bet.jack
=>
start.xml
bet.xml
and in each xml file I would like to write stuff according whats written in the jack file.
so actually I need to open the jack file, read from it, and then write to the xml file itself.
I hope I explained myself correctly.
My Code:
public String readFile(String filename)
{
String content = null;
File file = new File(filename);
try {
FileReader reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
I took this lines from stackoverflow, and it worked perfectly
File f = new File("your folder path here");// your folder path
//**Edit** It is array of Strings
String[] fileList = f.list(); // It gives list of all files in the folder.
for(String str : fileList){
if(str.endsWith(".jack")){
// Read the content of file "str" and store it in some variable
FileReader reader = new FileReader("your folder path"+str);
char[] chars = new char[(int) new File("your folder path"+str).length()];
reader.read(chars);
String content = new String(chars);
reader.close();
// now write the content in xml file
BufferedWriter bw = new BufferedWriter(
new FileWriter("you folder path"+str.replace(".jack",".xml")));
bw.write(content); //now you can write that variable in your file.
bw.close();
}
}
List all '.jack' files in a folder:
File folder = new File(path);
File[] files = folder.listFiles();
for (File file:files)
{
if (file.isFile() && file.getAbsolutePath().endsWith(".jack"))
{
System.out.println(file);
}
}
Replace extension:
String newPath = file.getAbsolutePath().replace(".jack", ".xml");
Create a new file and write to it:
PrintWriter writer = new PrintWriter("path to your file as string", "UTF-8");
writer.println("Your content for the new file...");
writer.close();
Putting all together:
File folder = new File(path);
File[] files = folder.listFiles();
for (File file:files)
{
if (file.isFile() && file.getAbsolutePath().endsWith(".jack"))
{
String newPath = file.getAbsolutePath().replace(".jack", ".xml");
PrintWriter writer = new PrintWriter(newPath, "UTF-8");
string content = readFile(file.getAbsolutePath());
// modify the content here if you need to modify it
writer.print(content);
writer.close();
}
}
Lots of good people have put code snippets online for this. Here is one
But, may I ask, why not just rename the file?
This link show howto.
I want to be able to scan all text files in a specified directory to look for a string. I know how to read through one text file. Thats quite easy but how do I make it scan all the content within a bunch of text files in a given directory?
The files will be all be named 0.txt 1.txt 2.txt etc, if that helps at all, perhaps using a counter to increase the name of the file searched then stopping it when there are no more txt files? that was my original idea but I can't seem to implement it
Thank you
You can use the following approach :
String dirName = "E:/Path_to_file";
File dir = new File(dirName);
File[] allFiles = dir.listFiles();
for(File file : allFiles)
{
// do something
}
This code snippet will do what you are looking for (possibly with a different charset of your choice):
File[] files = dir.listFiles();
for (File file : files) {
String t_text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
if (t_text.contains(search_string)) {
// do whatever you want
}
}
you could use this sample code to list all files under the directory
public File[] listf(String directoryName) {
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
}
And then after you retrieve each file, iterate through its lines with
LineIterator li = FileUtils.lineIterator(file);
boolean searchTermFound = false;
while(li.hasNext() && !searchTermFound) {
String sLine = li.next();
//Find the search term...
}
http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#lineIterator(java.io.File)
Try this:
public class FindAllFileFromDirectory {
static List<String> fileNames = new ArrayList<String>();
public static void main(String[] args) {
File AppDistributionDir = new File("<your directory path>");
if (AppDistributionDir.isDirectory()) {
listFilesForFolder(AppDistributionDir);
}
for (String s : fileNames) {
String fileExtension = FilenameUtils.getExtension(s); // import org.apache.commons.io.FilenameUtils;
//TODO: your condition hrere
if (s.equals("txt")) {
System.out.println(s);
}
}
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
//System.out.println(fileEntry.getAbsolutePath());
fileNames.add(fileEntry.getName());
}
}
}
}
Methodcall: scanFiles(new File("").getAbsolutePath(), "bla");
private static void scanFiles(String folderPath, String searchString) throws FileNotFoundException, IOException {
File folder = new File(folderPath);
//just do something if its a directory (otherwise possible nullpointerex # Files#listFiles())
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
// just scan for content if its not a directory (otherwise nullpointerex # new FileReader(File))
if (!file.isDirectory()) {
BufferedReader br = new BufferedReader(new FileReader(file));
String content = "";
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
content = sb.toString();
} finally {
br.close();
}
if (content.contains(searchString)) {
System.out.println("File " + file.getName() + " contains searchString " + searchString + "!");
}
}
}
} else {
System.out.println("Not a Directory!");
}
}
Additional information:
you could pass a FilenameFilter to this methodcall folder.listFiles(new FilenameFilter(){...})
i trying to save this string with a file list into a file but it only saves the last one.. what is the problem here? :(
public void fileprinter() throws IOException{
File dir = new File("c:");
String[] children = dir.list();
if (children == null) {
} else {
for (int i=0; i<children.length; i++) {
String filename = new StringBuffer().append(children[i]).toString();
System.out.println(filename);
Writer output;
File file = new File("D:/file.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(filename);
output.close();
}
}
}
You keep overwriting the same file in the loop, so only the last line will "survive".
Open the BufferedWriter outside of the loop (once!) and close it when done.
An alternative would be to open in append mode, but even then don't reopen the same file in a loop over and over again.