I am struggling to understand what i am doing wrong here. I have checked many times the file does exist and i cant get the For loop to find it. Debugging this section of code it says the path for the variable "folder" but says the filePath is null for that variable. I am very confused any help would be amazing.
String path = varablePath1;
File folder = new File(path);
if (folder.exists()){
System.out.println("got folder");
}
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
String FileNames = listOfFiles[i].getName();
FileWriter fw1 = new FileWriter(file1, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileNames);
bw1.newLine();
bw1.close();
}
}
you can Check Folder and File form Code and if Folder then get list of Folder and Write Using BufferedWriter. it works fine . please Check if any updation want .
public class Check {
public static void main(String args[]) throws IOException {
File f = null;
String path = "/home/ananddw";
f = new File(path);
if (f.isDirectory()) {
System.out.println("if");
File[] ss = f.listFiles();
for (File file : ss) {
if (file.isFile()) {
String FileFinalName = file.getName();
System.out.println(file.getName());
FileWriter fw1 = new FileWriter(file, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileFinalName);
bw1.newLine();
bw1.close();
}
}
} else if (f.isFile()) {
System.out.println("elkse");
}
}
}
what about the else piece in that verification, i.e:
if (folder.exists()){
System.out.println("got folder");
}
else {
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
String FileNames = listOfFiles[i].getName();
FileWriter fw1 = new FileWriter(file1, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileNames);
bw1.newLine();
bw1.close();
}
}
}
Related
i am creating temp file(outputFile) and writing text with BufferedWriter. i am not getting exception. But the String is not appended. I used sysout also for outputfile but it printing nothing.
File outputFile = File.createTempFile("abc",".tmp");
ArrayList<LoadDirectoryResponse> dirlist = new ArrayList<LoadDirectoryResponse>();
ArrayList<LoadDirectoryResponse> dirlistReq = new ArrayList<LoadDirectoryResponse>();
filenames = filenames.substring(0, filenames.length()-1);
String[] finalFileName = filenames.split(",");
dirlistReq = DataQuestService.mapLoadDirectoryList(lines,keyword,finalFileName);
for(MultipartFile multifile : files)
{
String fileName = multifile.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf("."));
File file = null;
file = File.createTempFile(fileName, prefix);
multifile.transferTo(file);
for(LoadDirectoryResponse obj: dirlistReq )
{
if(fileName.equals(obj.getFilename()))
{
LoadDirectoryResponse objRes = new LoadDirectoryResponse(obj.getFilename(),obj.getKeyWord(),obj.getLinesToBeCopied(),obj.isChecked());
Scanner sc = new Scanner(file);
if(obj.isChecked()) {
BufferedWriter br = new BufferedWriter(new FileWriter(outputFile));
ArrayList<String> linesToBeAdd = new ArrayList<String>();
int i = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
linesToBeAdd.add(line);
if(line.contains(obj.getKeyWord()))
{
String value = DataQuestService.getLinesToBeAdd(i,linesToBeAdd,lines);
br.write(value);
break;
}
else
{
objRes.setStatus("Not Found");
}
}
}
dirlist.add(objRes);
}
}
}
Scanner sc1 = new Scanner(outputFile);
while(sc1.hasNextLine())
{
System.out.println(sc1.nextLine());
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + outputFile.getName() + "\"")
.body(outputFile);
}
Please help with this
Thanks in Advance
When use the BufferedWriter you need to flush and close the writer.
You can use the try-with-resources in Java7+.
try (BufferedWriter br = new BufferedWriter(new FileWriter(outputFile))) {
// write something...
}
In this case, I recommend moving the BufferedWriter outside. Because you just output many files to temporary files.
// Your code ...
dirlistReq = DataQuestService.mapLoadDirectoryList(lines,keyword,finalFileName);
try (BufferedWriter br = new BufferedWriter(new FileWriter(outputFile))) {
for(MultipartFile multifile : files) {
String fileName = multifile.getOriginalFilename();
// Your code ...
}
}
// Your code ...
I have the following method to write a list into a CSV file using CSVWriter. Unfortunately, it does not separate them by comma which make them messy when I open it in Excel. How can I modify it?
private void generateCSV(List<String> dataset) throws IOException {
CSVWriter writer = null;
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(true);
if (chooser.showSaveDialog(chooser) == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
String file_name = f.toString();
if (!(file_name.endsWith(".csv"))) {
file_name += ".csv";
}
writer = new CSVWriter(new FileWriter(f));
for(int i=0; i< dataset.size(); i++){
String[] str = new String[] {dataset.get(i)};
writer.writeNext(str);
}
} else {
return;
}
writer.close();
}
You're creating a String[] for each element on your dataset in your for loop and then writing one element per each line with writeNext(). So they are not comma separated because it's just one element per line, using the line separator at the end of each line.
I think that this is what you want. Am I right?
private void generateCSV(List<String> dataset) throws IOException {
CSVWriter writer = null;
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(true);
if (chooser.showSaveDialog(chooser) == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
String file_name = f.toString();
if (!(file_name.endsWith(".csv"))) {
file_name += ".csv";
}
writer = new CSVWriter(new FileWriter(f));
String[] str = new String[dataset.size()];
for (int i = 0; i < dataset.size(); i++) {
str[i] = dataset.get(i);
}
writer.writeNext(str);
} else {
return;
}
writer.close();
}
Supposedly the user will enter their "ID #: 1203103" then after that it will automatically create a text file named 1203103.txt. How can I search the file name "1203103.txt" in the file directory?
String id = scan.nextLine();
File file = new File(id+".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
System.out.println("Enter the ID # to search: ");
You can try with this.
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:"); //file directory
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("1203103"); //here is you file name starts with. Or you can use name.equals("1203103.txt");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir does not exist or is not a directory");
}else {
for (int i=0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Hope this helps.
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID # to search: ")
String id=scan.next();
File f= new File(id+".txt");
if(f.exists() && !f.isDirectory()) {
System.out.println("file exist");
}else{
System.out.println("file doesn't exist");
}
Your code will create a new file if the file doesn't already exist. If the file does exist, it will be erased and an empty file created in it's place. In both cases, you will have a brand new, empty file. There is nothing to search.
you can browse all files within a directory (a file) using list (for String results) or listfiles (for file results)...
String directoryName = ...;
File directory = new File(directoryName);
File[] listOfAllFiles = directory.listFiles();
String[] listOfAllFileNames = directory.list();
Try this to search through all the files in a directory:
for (File file : folder.listFiles()) {
if (!file.isDirectory())
System.out.println(file.getName()); //Match here
}
You don't need to search for it. You already know its name, so just need to check if it exists, and optionally if it's a file and not a directory:
File file = new File(fileName);
if (file.exists() && file.isFile()) {
// ...
}
Try this :
public static void main(String[] args) throws IOException {
String id = "kick";
File file = new File(id + ".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
File folder = new File("C:\\Users\\kick\\Documents\\NetBeansProjects\\JavaApplication191");
// the list of files at specified folder
File[] listOfFiles = folder.listFiles();
// go through the list of files to see if you can find file was named kick
for (int i = 0; i < listOfFiles.length; i++) {
// gives you access to each elements of listofFiles array name
String filename = listOfFiles[i].getName();
if (filename.startsWith("kick")) {
System.out.println("found");
} else{
System.out.println("not found');
}
}
}
Quick Q
i have a loop that finds all the files in a directory, what i want to do is add a line of code into it that would write these results into a txt file, how would i best do this
current code :
public String FilesInFolder() {
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
}
}
return "";
}
You can use FileWriter and StringWriter together.
public String FilesInFolder() throws IOException {
FileWriter fw = new FileWriter("file.txt");
StringWriter sw = new StringWriter();
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
sw.write(files);
System.out.println(files);
}
}
fw.write(sw.toString());
fw.close();
return "";
}
With FileWritter and BufferedWriter:
public String FilesInFolder() {
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
File file = new File("output.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
bw.write(files);
}
}
bw.close();
return "";
}
here is a code to concatenate all files from a folder.
it works well but i modified it to delete files after concatenation and this function is not working coze i don't know how to declare in main method
Any help will be appreciated thank you very much.
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("Processing " + files[i].getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(files[i]
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
}
pw.close();
System.out.println("All files have been concatenated into concat.txt");
File directory = new File("C:/Target");
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
// Delete each file
if (!file.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+file);
}
}
}
}
First, make sure you have enough permission to be able to delete the contents in c:\target directory.
Second, if that directory contains subdirectories, you will need to delete all the files in each subdirectory first before you can perform a file.delete() on the subdirectory. You can do recursive deletion like this:-
public boolean deleteDirectory(File path) {
if (path.exists()) {
for (File file : path.listFiles()) {
if (file.isDirectory()) {
deleteDirectory(file);
}
else {
file.delete();
}
}
}
return path.delete();
}
Then, you can call deleteDirectory("C:/Target"); to perform the recursive deletion.
I am guessing this is something you copied from elsewhere. You declare File[] files twice - the second time just do
File directory = new File("C:/Target");
// Get all files in directory
files = directory.listFiles();
for (File toDelete : files)
{
// Delete each file
if (!toDelete.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+toDelete);
}
}
You could try just moving your delete to your first loop... like this,
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
File currentFile = files[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 concat.txt");
}