i have a code to concatenate txt files from a folder and move the concatenated file in another folder.
My code is working well but it deletes files after concatenating them so i would like to move these files to another folder just after concatenating them.
My files from c:\source must be moved to c:\Archive
It was my mistake at the starting, i wanted to move files but i delete them!!
And i would like to throw exception when there is no files in the source folder.
So my code is:
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Target/Filec.txt"));// directory where concatenated file are created
File file = new File("C:/Source");// where files have to be concatenated and move to c:\Archive before deleting
File[] files2 = file.listFiles();
for (int i = 0; i < files2.length; i++)
{
File currentFile = files2[i];
System.out.println("Processing " + currentFile.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(currentFile));
String line = br.readLine();
while (line != null)
{
pw.println(line);
line = br.readLine();
}
br.close();
if (!currentFile.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+ currentFile.getName());
}
}
pw.close();
System.out.println("All files have been concatenated into Filec.txt");
}
}
Thank you
To move a file you use source.renameTo(targetFile).
If there are no files in the source dir then listFiles() will return an empty array so just check for that and throw.
Also if you just want to blindly concat files you don't need to read line by line, just open a FileInputStream, read chunks into a byte[] and write using a FileOutputStream. Likely to be much more efficient and simpler.
You can move a file like so:
// File (or directory) to be moved
File file = new File("filename");
// Destination directory
File dir = new File("directoryname");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
// File was not successfully moved
}
Instead of File.delete() use FileUtils.moveFile() from apache commons
Related
I am trying to delete and rename a file however the delete() and rename() function does not work. I can't seem to find the bug in the code as it should run properly by logic (i think). Can anyone tell me why it can't delete a fill. this code works except deleting old txt and renaming temp.txt to old file.
public Boolean deleteItem(String item){
try{
// creating and opening file
File f = new File("temp.txt");
f.delete(); // to delete existing data inside file;
File old = new File(file);
FileWriter writer = new FileWriter(new File("temp.txt"), true);
FileReader fr = new FileReader(old);
BufferedReader reader = new BufferedReader(fr);
String s;
// creating temporary item object
String[] strArr;
//searching for data inside the file
while ((s = reader.readLine()) != null){
strArr = s.split("\\'");
if (!strArr[0].equals(item)){
writer.append(s + System.getProperty("line.separator"));
}
}
//rename old file to file.txt
old.delete();
boolean successful = f.renameTo(new File(file));
writer.flush();
writer.close();
fr.close();
reader.close();
return successful;
}
catch(Exception e){ e.printStackTrace();}
return false;
}
The logic seems a little tangled. Here's what I think it looks like.
You delete file.txt
You create a new file.txt and copy 'file' into it
You delete 'file'
You rename file.txt to 'file'
You close input and output files
My guess would be that your operating system (unspecified) is preventing deletes and renames of open files. Move the closing to before the delete/rename. And check the return from those functions.
Aside: as a minor improvement to readability, you don't need to keep calling 'new File(xxx)' with the same xxx. A File is just a representation of the name of the file. Do it once. And 'File tempFile = new File("file.txt")' would be easier to follow than calling it 'f'.
Don't use the old java.io.File. It is notorious for its lax error handling and useless error messages. Use the "newer" NIO.2 java.nio.file.Path and the java.nio.file.Files methods that were added in Java 7.
E.g. the file.delete() method returns false if the file was not deleted. No exception is thrown, so you'll never know why, and since you don't even check the return value, you don't know that it didn't delete the file either.
The file isn't deleted because you still have it open. Close the files before attempting to delete+rename, and do it using try-with-resources, also added in Java 7.
Your code should be the following, through capturing exceptions and turning them into a boolean return value is error-prone (see issue with file.delete()).
public boolean deleteItem(String item){
try {
// creating and opening file
Path tempFile = Paths.get("temp.txt");
Files.deleteIfExists(tempFile); // Throws exception if delete failed
Path oldFile = Paths.get(file);
try ( BufferedWriter writer = Files.newBufferedWriter(tempFile);
BufferedReader reader = Files.newBufferedReader(oldFile); ) {
//searching for data inside the file
for (String line; (line = reader.readLine()) != null; ) {
String[] strArr = line.split("\\'");
if (! strArr[0].equals(item)){
writer.append(line + System.lineSeparator());
}
}
} // Files are flushed and closed here
// replace file with temp file
Files.delete(oldFile); // Throws exception if delete failed
Files.move(tempFile, oldFile); // Throws exception if rename failed
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Basically you want to remove selected lines from a text file.
The following code uses the stream API1. It filters out all the unwanted lines and writes the lines that you do want to a temporary file. Then it renames the temporary file to your original file, thus effectively removing the unwanted lines from the original file. Note that I am assuming that your "global" variable file is a string.
/* Following imports required.
import java.io.File
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
*/
Path path = Paths.get(file);
final PrintWriter[] pws = new PrintWriter[1];
try {
File tempFile = File.createTempFile("temp", ".txt");
tempFile.deleteOnExit();
pws[0] = new PrintWriter(tempFile);
Files.lines(path)
.filter(l -> !item.equals(l.split("'")[0]))
.forEach(l -> pws[0].println(l));
pws[0].flush();
pws[0].close();
Files.move(tempFile.toPath(), path, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
finally {
if (pws[0] != null) {
pws[0].close();
}
}
1 Stream API was introduced in Java 8
When a file is opened in internet explorer without saving, it stores the file in temp folder. In windows 10 it creates a folder with random name in temp folder. I need to read the file using java. But java file api requires me to give the path of the file to read the contents of the file. How can I get the exact location of the file with the name that is stored by ie?
I tried using the java.io.tmpdir but it doesn't refer to the folder where the file is stored.
BufferedReader br = new BufferedReader(new FileReader(path to the file));
try {
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();
} finally {
br.close();
}
I expect exact file name and the path to the file location.
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 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);
}
}
File read = new File("Numbers.txt");
Scanner inputFile = new Scanner(read);
while(inputFile.hasNext())
{
sum = inputFile.nextDouble() + sum;
count++;
}
inputFile.close();//close the input file
I'm trying to read data out of the text file Numbers.txt and the following code compiles fine but I get the Java.io.FileNotFoundException error when the program runs. I've also tried entering the full file path but I might have done it wrong. Any ideas?
Make Sure your text file is in the folder with your java file
because you used the direct path .
and try this code check, if still not working .
BufferedReader read = new BufferedReader(new FileReader("yourTextFile.txt"));
String line = read.readLine();
while(line !=null)
{
System.out.println(line);
line=read.readLine();
}
}catch(Exception ex)
{System.out.println(ex.getMessage());}
Try adding
System.out.println("Full path is " + read.getCanonicalPath()
+ ", canRead=" + read.canRead()
+ ", exists=" + read.exists());
and then see whether the full path exists on your file system, and whether it is readable according to canRead.
If the file is a symlink, canRead might return true in that the symlink is resolvable even though the file to which the link points is unreadable. To deal properly with symlinks you really need to use the new java.nio.file APIs.