I have a folder called attachment which contains 5 .gif images and i have a att.txt which contains name for this .gif images, Now i need to rename these images with the name present in att.txt.
Below is the code i tried.Please help
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader br = new java.io.BufferedReader(new FileReader("D:\\template_export\\template\\attachments"));
String sCurrentLine="";
while ((sCurrentLine = br.readLine()) != null) {
sCurrentLine= sCurrentLine.replaceAll("txt", "gif");
String[] s = sCurrentLine.split(",");
for(int i=0;i<s.length;i++){
new File("D:\\template_export\\template\\attachment_new"+s[i]).mkdirs();
System.out.println("Folder Created");
}
}
}
Try this:
public class Tst {
public static void main(String[] args) {
File orgDirectory = new File("attachements");// replace this filename
// with the path to the folder
// that contains the original images
String fileContent = "";
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachements.txt")))) {
for (String line; (line = br.readLine()) != null;) {
fileContent += line;
}
} catch (Exception e) {
e.printStackTrace();
}
String[] newLocations = fileContent.split(" ");
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
File destinationFolder = new File("processed");
int max = Math.min(orgFiles.length, newLocations.length);
for (int i = 0; i < max; i++) {
String newLocation = newLocations[i];
int lastIndex = newLocation.lastIndexOf("/");
if (lastIndex == -1) {
continue;
}
String newDirName = newLocation.substring(0, lastIndex);
String newName = newLocation.substring(lastIndex);
File newDir = new File(destinationFolder, newDirName);
if (!newDir.exists()) {
newDir.mkdir();
}
try {
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It probably won't work since your description isn't that clear but I hope you get the idea and you understand how this task can be done. The important parts are:
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
Which creates a File array which contains all the "gif" files in the source directory.
And:
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
Which mover the original image to the new directory and sets its name to the one retrieved from the "attachements.txt" file.
Related
I have this method here, I want to look in a folder recursively to count files that startsWith "D".
It is showing me the StackOverflowError.
public void CountThem() throws FileNotFoundException, IOException{
int count = 0;
File []files = file.listFiles();
for(File f : files){
if(f.isDirectory()){
CountThem();
}else{
if(f.getName().startsWith("D")){
count++;
}
}
}
}
It's because when a File is a directory, you're starting over your function, that makes an infinite loop. You would have to define the function, that takes a File as a parameter:
public int countThem(File file) throws FileNotFoundException, IOException{
int count = 0;
File []files = file.listFiles();
for(File f : files){
if(f.isDirectory()) {
count += countThem(f);
} else {
if(f.getName().startsWith("D")) {
count++;
}
}
}
return count;
}
P.S.: In java it's a standard to start method names lowercase.
Edit:
public class Fajlla {
File folder;
FileReader fr;
BufferedReader br;
PrintWriter pw;
public Fajlla(String fld)throws IOException{
folder = new File(fld);
if(!folder.isDirectory()){
throw new IOException("Nuk eshte folder");
}
pw = new PrintWriter(new File("C:/Users/Admin/Desktop/dreniii.txt"));
}
public int callItOUU() throws IOException{
return this.countThem(folder);
}
public int countThem(File folder){
int count = 0;
File [] files = folder.listFiles();
for (File file : files) {
if(file.isDirectory()){
count+=countThem(file);
}if(file.isFile() && file.canRead()){
count++;
}
}
return count;
}
public static void main(String[] args) {
try {
Fajlla f = new Fajlla("C:/Users/Admin/Desktop/New folder");
int count = f.callItOUU(new File("C:/Users/Admin/Desktop/dreniii.txt"));
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Fajlla.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is the full code
public class Fajlla {
File folder;
FileReader fr;
BufferedReader br;
PrintWriter pw;
public Fajlla(String fld)throws IOException{
folder = new File(fld);
if(!folder.isDirectory()){
throw new IOException("Nuk eshte folder");
}
pw = new PrintWriter(new File("C:/Users/Admin/Desktop/dreniii.txt"));
}
public int callItOUU() throws IOException{
return this.countThem(folder);
}
public int countThem(File folder){
int count = 0;
File [] files = folder.listFiles();
for (File file : files) {
if(file.isDirectory()){
count+=countThem(folder);
}if(file.isFile() && file.canRead()){
count++;
}
}
return count;
}
public static void main(String[] args) {
try {
Fajlla f = new Fajlla("C:/Users/Admin/Desktop/New folder");
int count = f.callItOUU();
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Fajlla.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Does Asterisk work in java? I want to read a file with timestamp.
taxonomy_timestamp.txt but it doesn't work.
String fileName = "20190215/"+"taxonomy_*.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
if(line.contains(":")) {
String[] segmentData = line.split(":");
String keyword = segmentData[0];
String name = segmentData[1];
segmentList.add(new ExternalSegmentDownloader.ExternalSegmentKey(keyword, name));
}
}
}catch(IOException e){
log.info("File not found.",e);
}
return segmentList;
}
Try this.
public static void main(String[] args) throws IOException {
File directory = new File(".");
File[] files = directory.listFiles();
System.out.println("All files and directories:");
displayFiles(files);
String pattern = "20190215/"+"taxonomy_[*].txt";
System.out.println("\nFiles that match regular expression: " + pattern);
FileFilter filter = new RegexFileFilter(pattern);
files = directory.listFiles(filter);
displayFiles(files);
}
public static void displayFiles(File[] files) {
for (File file : files) {
System.out.println(file.getName());
}
}
Hi I have Text file having some tag based data and i want to split into multiple text files.
Main Text files having data like this:
==========110CYL067.txt============
<Entity Text>Cornell<Entity Type>Person
<Entity Text>Donna<Entity Type>Person
<Entity Text>Sherry<Entity Type>Person
<Entity Text>Goodwill<Entity Type>Organization
==========110CYL068.txt============
<Entity Text>Goodwill Industries Foundation<Entity Type>Organization
<Entity Text>Goodwill<Entity Type>Organization
NOTE: Over here 110CYL068.txt and 110CYL067.txt are text files.
I want to split this file into 110CYL068.txt and 110CYL067.txt and so on.
This ============ pattern is fixed.Between ============ FileName ============
file name could be anything.does anyone have any insight.
I don't want to write codes for you, so you can read the file using a BufferedReader or FileReader. You can create and write to a new File using any file writer whenever you see a line starting with ======= or containing .txt.
If you encounter those close the previous file and repeat the process.
Done ppl way to complicatet just did it fast and dirty.
public static List<String> lines = new ArrayList<String>();
public static String pattern = "==========";
public static void main(String[] args) throws IOException {
addLines(importFile());
}
private static List<String> importFile() throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
lines.add(line.replaceFirst(pattern, ";") + "\n");
line = br.readLine();
}
} finally {
br.close();
}
return lines;
}
private static void addLines(List<String> list) throws IOException {
String FilesString = list.toString();
System.out.println(FilesString);
String[] FilesArray = FilesString.split(";");
for (String string : FilesArray) {
createFile(string);
}
}
private static void createFile(String content) throws IOException {
String[] Lines = content.replaceAll("=", "").split("\n");
File file = new File("C:\\temp\\" + Lines[0]);
file.createNewFile();
FileWriter writer = new FileWriter(file);
Lines[0] = null;
for (String Line : Lines) {
if (Line != null) {
writer.append(Line.replace(",", "")+"\n");
}
}
writer.flush();
writer.close();
}
}
Also quick and dirty, not using regex. I don't really recommend doing it like this because the for loop in main is quite confusing and could break, but it might be beneficial to use this for ideas.
import java.io.*;
import java.util.*;
class splitFiles {
public static void main(String[] args){
try {
List<String> fileRead = readFiles("some.txt");
for(int i=0; i<fileRead.size(); i++){
if(fileRead.get(i).charAt(0) == '='){
PrintWriter writer = new PrintWriter(getFileName(fileRead.get(i)), "UTF-8");
for(int j=i+1; j<fileRead.size(); j++){
if(fileRead.get(j).charAt(0) == '='){
break;
} else {
writer.println(fileRead.get(j));
}
}
writer.close();
}
}
} catch (Exception e){
}
}
public static String getFileName(String fileLine){
String[] split = fileLine.split("=");
for(String e: split){
if(e.isEmpty()){
continue;
} else {
return e;
}
}
return "No file name found";
}
public static ArrayList<String> readFile(String path){
try {
Scanner s = new Scanner(new File(path));
ArrayList<String> list = new ArrayList<String>();
while(s.hasNext()){
list.add(s.next());
}
s.close();
return list;
} catch (FileNotFoundException f){
System.out.println("File not found.");
}
return null;
}
static List<String> readFiles(String fileName) throws IOException {
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
return words;
}
}
i want to populate Folder Name With Sub Folder name on KendoDrop Down . so i want to Convert Folder Directory in JSOn Format How can i Do That ?
public class FolderPath {
public static void main(String[] args) throws IOException {
File currentDir = new File("Folder URL "); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
sb1 = sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
String str = file.getCanonicalPath();
displayDirectoryContents(file);
} else {
}
}
sb1.deleteCharAt(sb1.length() - 1);
sb1 = sb1.append("]");
System.out.println("s2==>" + sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here i am Not Getting Full Directroy into JSOn Please Help
You are creating a StringBuilder object on each iteration. That's why your concatenation does not work.
Consider the contents of you C:\test is composed of 3 directories:
c:\test
|
+--css
| +--less
+--js
The code below, returns:
[{"JSONKEY":"C:\test\css"},
{"JSONKEY":"C:\test\css\less"},
{"JSONKEY":"C:\test\js"}]
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class FolderPath {
private static FileFilter onlyDirectories = new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
};
public static void main(String[] args) {
File currentDir = new File("C:\\test"); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
doDisplayDirectoryContents(dir, sb1);
if (sb1.length() > 1) {
sb1.deleteCharAt(sb1.length() - 1);
}
sb1.append("]");
System.out.println(sb1);
}
private static void doDisplayDirectoryContents(File dir, StringBuilder sb1) {
File[] files = dir.listFiles(onlyDirectories);
if (files != null) {
for (File file : files) {
try {
sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
doDisplayDirectoryContents(file, sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public List<Object> getDirectoryContents(String path) throws IOException {
File directory = new File(path);
File[] files;
enter code here FileFilter fileFilter = file -> file.isDirectory() || file.isFile();
files = directory.listFiles(fileFilter);
List<Object> directoryContent = new ArrayList<>();
if(files != null) {
for (int i = 0; i < files.length; i++) {
File filename = files[i];
String folderPath[] =filename.toString().split("/");
if(files[i].isDirectory()) {
Folder folder = new Folder();
folder.setName(folderPath[folderPath.length - 1]);
folder.setType("folder");
folder.setChildren(mapper.readTree(mapper.writeValueAsString(getDirectoryContents(path + "/" + folder.getName()))));
directoryContent.add(folder);
}
else{
Files file = new Files();
file.setName(folderPath[folderPath.length - 1]);
file.setType("file");
directoryContent.add(file);
}
}
}
return directoryContent;
}
public class Files {
private String name;
private String type = "file";
}
public class Folder {
private String name;
private String type = "folder";
private JsonNode children;
}
I'm trying to print '1' or '0' in text view if it passes the if statements. I ran it in the debug mode, and it all works, but it is not printing in the text view. How do I fix this I tried a lot of stuff, but I'm still stuck.
public class Readcsv {
private static final String FILE_DIR = "/Users/Me/Downloads";
private static final String FILE_TEXT_NAME = ".csv";
public static void main(String [] args) throws Exception{
PrintWriter writer = new PrintWriter("/users/Me/Documents/Test.txt", "UTF-8");
int i=-1;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
//Find Number of Files
String[] list = new Readcsv().FileCount(FILE_DIR, FILE_TEXT_NAME);
System.out.println("Total Files = " + list.length);
while(i++ < list.length){
System.out.println("Loop Count = " + i);
try {
br = new BufferedReader(new FileReader("/users/Tanuj/Downloads/" + list[i]));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] strRecord = line.split(cvsSplitBy);
if (!strRecord[0].equals("timestampMs")){
int c = Integer.parseInt(strRecord[4]);
int e = Integer.parseInt(strRecord[5]);
if(c>e){
writer.print("1");
}
else{
writer.print("0");
}
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} //End of while
writer.close();
} //End of Main
public String[] FileCount(String folder, String ext) {
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
if(dir.isDirectory()==false){
System.out.println("Directory does not exists : " + FILE_DIR);
return null;
}
// list out all the file name and filter by the extension
String[] list = dir.list((FilenameFilter) filter);
return list;
}
// inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
have you tryed BufferedWriter?
File file = new File("Test.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("something");
bw.newLine();
bw.close();