So i want my program to write all files containing ".txt" to "out.txt". But wr.close() ends my writer and it only writes the files from one folder and not from all. Need help.
import java.io.*;
public class Prv {
public static void main(String[] args) throws InterruptedException, IOException{
String a=".";
String b="D:\\JavaProjects\\Auditoriski\\.\\Out.txt";
Pomini(a,b);
}
public static void Pomini(String in, String out) throws IOException {
File file = new File(in);
BufferedWriter wr = new BufferedWriter(new FileWriter(out));
if(file.exists()) {
File[] subfiles = file.listFiles();
for(File f : subfiles) {
if(f.isDirectory()) {
Pomini(f.getAbsolutePath(), out );
}
if(f.getName().contains(".txt")) {
System.out.print(f.getName());
System.out.println();
wr.write(f.getName());
wr.newLine();
}
}
}
wr.close();
}
}
You just need to create BufferedWriter and close it outside of your Pomini method and pass it as a parameter.
try (BufferedWriter wr = new BufferedWriter(new FileWriter(out));) {
Pomini(a, b, wr);
}
public static void Pomini(String in, String out, BufferedWriter wr) throws IOException {
File file = new File(in);
if(file.exists()) {
File[] subfiles = file.listFiles();
for(File f : subfiles) {
if(f.isDirectory()) {
Pomini(f.getAbsolutePath(), out, wr);
}
if(f.getName().contains(".txt")) {
System.out.print(f.getName());
System.out.println();
wr.write(f.getName());
wr.newLine();
}
}
}
}
Related
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);
}
}
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();
}
}
}
In the program below I'm currently reading files in a directory. However I'd like to only read .txt files. How can I read only the .text files located in the directory.
import java.io.*;
public class Data {
public static void main(String[] args) throws IOException {
String target_dir = "C:\\Files";
String textfile;
File dir = new File(target_dir);
File[] files = dir.listFiles();
for (File textfiles : files) {
if (textfiles.isFile()) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(textfiles));
String line;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
}
You can use java.io.FilenameFilter to filter files in a directory.
import java.io.*;
public class Data {
public static void main(String[] args) throws IOException {
String target_dir = "C:\\Files";
File dir = new File(target_dir);
FilenameFilter textFileFilter = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File[] files = dir.listFiles(textFileFilter);
for (File textfiles : files) {
if (textfiles.isFile()) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(textfiles));
String line;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
}
Try checking the extension
import java.io.*;
public class Data {
public static void main(String[] args) throws IOException {
String target_dir = "C:\\Files";
String textfile;
File dir = new File(target_dir);
File[] files = dir.listFiles();
for (File textfiles : files) {
if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(textfiles));
String line;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
}
Use Files.probeContentPath() to get a mime of the file.
You can use a FileNameFilter to do that work for you. Your code could look like this:
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
if (name.toLowerCase().endsWith(".txt")) return true;
return false;
}
});
Then you know that files contains only files that end with .txt, or whatever other conditions you need.
I like the DirectoryScanner method which uses ant.jar.
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.txt"});
scanner.setBasedir("C:\\Files");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
This is from Misha Here. But as you can see there are many ways to do this.
Write a method that returns all the .txt files in a given directory.
import java.io.File;
import java.io.FilenameFilter;
public class Data {
public File[] finder( String dirName){
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename)
{ return filename.endsWith(".txt"); }
} );
}
public static void main(String[] args) throws IOException {
String target_dir = "C:\\Files";
String textfile;
File dir = new File(target_dir);
File[] files = finder(target_dir);
for (File textfiles : files) {
if (textfiles.isFile() && textfiles.getName().endsWith("txt")) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(textfiles));
String line;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
}
DIR* dir = opendir("."); // to open current dir
entity = readdir(dir);
while(entity != NULL){
sprintf(filename,"%s", entity->d_name);
len = strlen(filename);
if(strcmp(filename+len-4,".txt")) {entity = readdir(dir); continue;}
// operation to execute.
entity = readdir(dir);
}
//like this also we can do this task
I am a beginner at programming with Java and am currently writing an application which must be able to compress and decompress .zip files. I can use the following code to decompress a zipfile in Java using the built-in Java zip functionality as well as the Apache Commons IO library:
public static void decompressZipfile(String file, String outputDir) throws IOException {
if (!new File(outputDir).exists()) {
new File(outputDir).mkdirs();
}
ZipFile zipFile = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File entryDestination = new File(outputDir, entry.getName());
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
InputStream in = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(entryDestination);
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
How would I go about creating a zipfile from a directory using no external libraries other than what I am already using? (Java standard libraries and Commons IO)
The following method(s) seem to successfully compress a directory recursively:
public static void compressZipfile(String sourceDir, String outputFile) throws IOException, FileNotFoundException {
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile));
compressDirectoryToZipfile(sourceDir, sourceDir, zipFile);
IOUtils.closeQuietly(zipFile);
}
private static void compressDirectoryToZipfile(String rootDir, String sourceDir, ZipOutputStream out) throws IOException, FileNotFoundException {
for (File file : new File(sourceDir).listFiles()) {
if (file.isDirectory()) {
compressDirectoryToZipfile(rootDir, sourceDir + File.separator + file.getName(), out);
} else {
ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir, "") + file.getName());
out.putNextEntry(entry);
FileInputStream in = new FileInputStream(sourceDir + file.getName());
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
}
}
}
As seen in my compression code snippet, I'm using IOUtils.copy() to handle stream data transfer.
I fix above error and it works perfect.
public static void compressZipfile(String sourceDir, String outputFile) throws IOException, FileNotFoundException {
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile));
Path srcPath = Paths.get(sourceDir);
compressDirectoryToZipfile(srcPath.getParent().toString(), srcPath.getFileName().toString(), zipFile);
IOUtils.closeQuietly(zipFile);
}
private static void compressDirectoryToZipfile(String rootDir, String sourceDir, ZipOutputStream out) throws IOException, FileNotFoundException {
String dir = Paths.get(rootDir, sourceDir).toString();
for (File file : new File(dir).listFiles()) {
if (file.isDirectory()) {
compressDirectoryToZipfile(rootDir, Paths.get(sourceDir,file.getName()).toString(), out);
} else {
ZipEntry entry = new ZipEntry(Paths.get(sourceDir,file.getName()).toString());
out.putNextEntry(entry);
FileInputStream in = new FileInputStream(Paths.get(rootDir, sourceDir, file.getName()).toString());
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
}
}
}
Looks like the answer is a bit outdated. Refreshed it for latest Java for now.
Also in ZIP file file names will be relative to given folder for compression. In original answer they were absolute with full paths.
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zipper {
public static void compressFolder(String sourceDir, String outputFile) throws IOException {
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(outputFile))) {
compressDirectoryToZipFile((new File(sourceDir)).toURI(), new File(sourceDir), zipOutputStream);
}
}
private static void compressDirectoryToZipFile(URI basePath, File dir, ZipOutputStream out) throws IOException {
List<File> fileList = Files.list(Paths.get(dir.getAbsolutePath()))
.map(Path::toFile)
.collect(Collectors.toList());
for (File file : fileList) {
if (file.isDirectory()) {
compressDirectoryToZipFile(basePath, file, out);
} else {
out.putNextEntry(new ZipEntry(basePath.relativize(file.toURI()).getPath()));
try (FileInputStream in = new FileInputStream(file)) {
IOUtils.copy(in, out);
}
}
}
}
}
Full class ZipUtils based on answers above.
public final class ZipUtils {
private ZipUtils() {
}
// For testing
public static void main(String[] args) throws IOException {
compressFile(new File("./file.test"), new File("test1.zip"));
compressDirectory(new File("./test1"), new File("test2.zip"));
extractArchive(new File("./test2"), new File("test3.zip"));
}
public static void compressDirectory(File sourceDirectory, File zipFile) throws IOException {
Preconditions.checkState(sourceDirectory.exists(), "Source directory is not exists: %s", sourceDirectory);
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) {
compressDirectory(sourceDirectory.getAbsoluteFile(), sourceDirectory, out);
}
}
private static void compressDirectory(File rootDir, File sourceDir, ZipOutputStream out) throws IOException {
for (File file : Preconditions.checkNotNull(sourceDir.listFiles())) {
if (file.isDirectory()) {
compressDirectory(rootDir, new File(sourceDir, file.getName()), out);
} else {
String zipEntryName = getRelativeZipEntryName(rootDir, file);
compressFile(out, file, zipEntryName);
}
}
}
private static String getRelativeZipEntryName(File rootDir, File file) {
return StringUtils.removeStart(file.getAbsolutePath(), rootDir.getAbsolutePath());
}
public static void compressFile(File file, File zipFile) throws IOException {
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) {
compressFile(out, file, file.getName());
}
}
private static void compressFile(ZipOutputStream out, File file, String zipEntityName) throws IOException {
ZipEntry entry = new ZipEntry(zipEntityName);
out.putNextEntry(entry);
try (FileInputStream in = new FileInputStream(file)) {
IOUtils.copy(in, out);
}
}
public static void extractArchive(File targetDirectory, File zipFile) throws IOException {
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
extractStream(targetDirectory, zis);
}
}
private static void extractStream(File targetDirectory, ZipInputStream zis) throws IOException {
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
extractEntry(targetDirectory, zis, zipEntry);
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
}
private static void extractEntry(File targetDirectory, ZipInputStream zis, ZipEntry zipEntry) throws IOException {
File newFile = newFile(targetDirectory, zipEntry);
if (zipEntry.isDirectory()) {
FileUtils.forceMkdir(newFile);
} else {
FileUtils.forceMkdirParent(newFile);
try (FileOutputStream fos = new FileOutputStream(newFile)) {
IOUtils.copy(zis, fos);
}
}
}
private static File newFile(File targetDirectory, ZipEntry zipEntry) throws IOException {
File targetFile = new File(targetDirectory, zipEntry.getName());
String targetDirPath = targetDirectory.getCanonicalPath();
String targetFilePath = targetFile.getCanonicalPath();
if (!targetFilePath.startsWith(targetDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return targetFile;
}
}
I am trying to create a file from a log report. To save the file I've created a button. When the button is pushed, the following code is executed:
public void SAVE_REPORT(KmaxWidget widget){//save
try {
String content = report.getProperty("TEXT");
File file = new File("logKMAX.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} //SAVE_REPORT
I have no compilation errors, but there isn't any file saved.
Any idea on what might be wrong?
Use the new file API. For one, in your program, you don't verify the return value of .createNewFile(): it doesn't throw an exception on failure...
With the new file API, it is MUCH more simple:
public void saveReport(KmaxWidget widget)
throws IOException
{
final String content = report.getProperty("TEXT");
final Path path = Paths.get("logKMAX.txt");
try (
final BufferedWriter writer = Files.newBufferedWriter(path,
StandardCharsets.UTF_8, StandardOpenOption.CREATE);
) {
writer.write(content);
writer.flush();
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class moveFolderAndFiles
{
public static void main(String[] args) throws Exception
{
File sourceFolder = new File("c:\\Audio Bible");
copyFolder(sourceFolder);
}
private static void copyFolder(File sourceFolder) throws Exception
{
File files[] = sourceFolder.listFiles();
int i = 0;
for (File file: files){
if(file.isDirectory()){
File filter[] = new File(file.getAbsolutePath()).listFiles();
for (File getIndividuals: filter){
System.out.println(i++ +"\t" +getIndividuals.getPath());
File des = new File("c:\\audio\\"+getIndividuals.getName());
Files.copy(getIndividuals.toPath(), des.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
}