how to read the data from the files of a directory - java

public class FIlesInAFolder {
private static BufferedReader br;
public static void main(String[] args) throws IOException {
File folder = new File("C:/filesexamplefolder");
FileReader fr = null;
if (folder.isDirectory()) {
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isFile()) {
try {
fr = new FileReader(folder.getAbsolutePath() + "\\" + fileEntry.getName());
br = new BufferedReader(fr);
System.out.println(""+br.readLine());
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
br.close();
fr.close();
}
}
}
}
}
}
how to print the first word from first file of a directory and the second word from second file and third word from a third file of the same directory.
i am able to open directory and print the line from each file of the directory,
but tell me how to print the first word from first file and second word from second file and so on . .

Something like the below will read first word from first file, second word from second file, ... nth word from nth file. You'll likely want to do some additional work to improve the codes stability.
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
public class SOAnswer {
private static void printFirst(File file, int offset) throws FileNotFoundException, IOException {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
while ( (line = br.readLine()) != null ) {
String[] split = line.split(" ");
if(split.length >= offset) {
String targetWord = split[offset];
}
// we do not care if files are read that do not match your requirements, or
// for reading complete files as you only care for the first word
break;
}
br.close();
fr.close();
}
public static void main(String[] args) throws Exception {
File folder = new File(args[0]);
if(folder.isDirectory()) {
int offset = 0;
for(File fileEntry : folder.listFiles()) {
if(fileEntry.isFile()) {
printFirst(fileEntry, offset++); // handle exceptions if you wish
}
}
}
}
}

Related

Add data to specific record in CSV file

I have a record in a CSV file and i am trying to add some extra info (a name) to the same specific record with the following code but it does not work. There is no error shown but the info i am trying to add just does not appear. What am i missing ?
public class AddName {
public static void main(String[] args) {
String filepath="Zoo.csv";
String editTerm="Fish";
String addedName="Ron";
addToRecord(filepath,editTerm,addedName);
}
public static void addToRecord(String filepath,String editTerm,String addedName){
String animal= "";
try{
FileWriter fw=new FileWriter(filepath,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
if (animal.equals(editTerm)){
pw.println(editTerm+","+addedName);
pw.flush();
pw.close();
}
System.out.println("Your Record was saved");
}
catch(Exception e){
System.out.println("Your Record was not saved");
e.printStackTrace();
}
}
You could consider using a CSV library to help you out with parsing CSVs because it is more complicated than it looks, especially when it comes down to quoting.
Here's a quick example using OpenCSV that clones the original CSV file and adds "Ron" as necessary:
public class Csv1 {
public static void main(String[] args) throws IOException, CsvValidationException {
addToRecord("animal.csv", "animal-new.csv", "fish", "Ron");
}
public static void addToRecord(String filepathIn, String filepathOut, String editTerm, String addedName)
throws IOException, CsvValidationException {
try (CSVReader reader = new CSVReader(new FileReader(filepathIn))) {
try (CSVWriter writer = new CSVWriter(new FileWriter(filepathOut))) {
String[] values;
while ((values = reader.readNext()) != null) {
if (values.length > 2 && values[0].equals(editTerm)) {
values[1] = addedName;
}
writer.writeNext(values);
}
}
}
}
}
Given the file:
type,name,age
fish,,10
cat,,12
lion,tony,10
will produce:
"type","name","age"
"fish","Ron","10"
"cat","","12"
"lion","tony","10"
(You can look for answers about outputting quotes in the resulting CSV)
Here the requirement is to add an extra column if the animal name matches. It's equivalent to changing a particular line in a file. Here's a simple approach to achieve the same, (Without using any extra libraries),
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class EditLineInFile {
public static void main(String[] args) {
String animal = "Fish";
Path path = Paths.get("C:\\Zoo.csv");
try {
List<String> allLines = Files.readAllLines(path);
int counter = 0;
for (String line : allLines) {
if (line.equals(animal)) {
line += ",Ron";
allLines.set(counter, line);
}
counter++;
}
Files.write(path, allLines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You may use this code to replace the file content "Fish" to "Fish, Ron"
public static void addToRecord(String filepath, String editTerm, String addedName) {
try (Stream<String> input = Files.lines(Paths.get(filepath));
PrintWriter output = new PrintWriter("Output.csv", "UTF-8"))
{
input.map(s -> s.replaceAll(editTerm, editTerm + "," + addedName))
.forEachOrdered(output::println);
} catch (IOException e) {
e.printStackTrace();
}
}

FileWriter / BufferedReader Java word finder

I have this code set up and I am trying to write a program that looks through a file and finds a specific hidden secret word then replaces the word with "found!" then re-prints the text file in the console. I know how to use reader and writer but I am unsure how i can use them in unison to do this. Code is as follows:
Reader Class:
package Main;
import java.io.*;
public class Read {
private static String line;
FileReader in;
File file;
public Read() {
line = "";
}
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line);
}
in.close();
}
public String getLine() {
return line;
}
public File getFile() {
return file;
}
}
Writer(change) class:
package Main;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Change {
public static void main(String[] args) throws IOException{
Read r = new Read();
String line = r.getLine();
FileWriter fw = new FileWriter(r.getFile());
while(line != null) {
if(line.equals("example")) {
fw.write("found!");
}
System.out.println(line);
}
}
}
Am i on the right path or should i combine both of these into one class. Also is this the proper way of writing to a specific line in a text file?
If the file is a reasonable size, you can read it into memory, change what you need and write it back out again:
public static void replaceOccurrences(String match, String replacement, Path path) throws IOException {
Files.write(path, Files.lines(path).map(l -> {
if(l.contains(match)) {
return l.replace(match, replacement);
} else {
return l;
}
}).collect(Collectors.toList()));
}
Alternatively, if you know that the search term occurs only once and you just need to find the position of the occurrence, use the following:
try(BufferedReader reader = Files.newBufferedReader(path)) {
int lineIndex = 0;
String line;
while(!(line = reader.readLine()).contains(match)) {
lineIndex++;
}
System.out.println(lineIndex); // line which contains match, 0-indexed
System.out.println(line.indexOf(match)); // starting position of match in line, 0-indexed
}
If all you have to do is print the converted text to system out (rather than writing it out to a file), the second class isn't really needed. You can accomplish what you need in the readFile() method of the Read class:
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line.replaceAll("example", "found!"));
}
in.close();
}
There are a lot of other tweaks you could make, but that's the core of the functionality you specified in your question.

I need help reading data from all files in a directory

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);
}
}

Java .jar fails to start because of loading jcombobox data from file

I am beginner with Java and I have tried to make my app better.
So I have a method to fill the jcombobox with items from text file.
The method is
private void fillComboBox(JComboBox combobox, String filepath) throws FileNotFoundException, IOException {
BufferedReader input = new BufferedReader(new FileReader(filepath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filepath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
for (int i = 0; i < lineArray.length - 1; i++) {
combobox.addItem(lineArray[i]);
}
}
And I am using it correctly
fillComboBox(jCombobox1, "items");
the text file with items is in my root directory of netbeans project.
It works perfectly when running the app from netbeans. But when I build the project and create .jar file. It does not run. I tried to run it from comand line.
This is what I got.
java.io.FileNotFoundException: items(System cannot find the file.)
How to deal with this? I didnt found anything. I dont know where is problem since it works nice in netbeans. Thank you very much for any help.
Is the .jar file in the same root directory?
Your exported .jar file might be working from a different directory, and not be able to find the text file.
Try placing the exported Jar in the same directory as the text file.
My example:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
public class test {
public static void main(String[] args) throws FileNotFoundException, IOException{
JComboBox box = new JComboBox();
fillComboBox(box, "C:\\path\\test.txt");
JOptionPane.showMessageDialog(null, box);
}
private static void fillComboBox(JComboBox combobox, String filepath) throws FileNotFoundException, IOException {
BufferedReader input = new BufferedReader(new FileReader(filepath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filepath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[] {});
for (int i = 0; i < lineArray.length - 1; i++) {
combobox.addItem(lineArray[i]);
}
}
}

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.

Categories