How to read a text file with timestamp? in Java - java

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

Related

I want to split textfile into mutilple text files

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

Mapping name from .txt to a folder in java

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.

How to Convert List of Folders and SubFolder into JSOn FOrmat

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

Why is the value not printing in the text view?

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

ADF Read Data From txt File And Assign to Variable

I would like to extract data from text file and assign it into variable before they can commit to database. I able to read all the data inside the text file, unfortunately i fail to separate them and assign to certain variable. My code as below:
private RichInputFile inputFile;
private UploadedFile file;
private String fileContent;
private String fileName;
private InputStream inputstream;
public void onFileUploadValueChangeListener(ValueChangeEvent valueChangeEvent) {
resetValue();
file = (UploadedFile)valueChangeEvent.getNewValue();
try {
inputstream = file.getInputStream();
System.out.println("inputstream Name: " +inputstream);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onUploadFile(ActionEvent actionEvent) {
if (file != null && inputstream != null) {
fileName = file.getFilename();
System.out.println("Notepad Name: " +fileName);
StringWriter writer = new StringWriter();
try {
IOUtils.copy(inputstream, writer);
fileContent = writer.toString();
System.out.println("File Content: " +fileContent);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Notepad Content: " +writer);
}
if (inputFile != null) {
inputFile.resetValue();
inputFile.setValid(true);
}
}
public void resetValue() {
if (fileName != null)
fileName = null;
if (fileContent != null)
fileContent = null;
if (inputstream != null)
inputstream = null;
}
public void setInputFile(RichInputFile inputFile) {
this.inputFile = inputFile;
}
public RichInputFile getInputFile() {
return inputFile;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public UploadedFile getFile() {
return file;
}
public String getFileContent() {
return fileContent;
}
public String getFileName() {
return fileName;
}
Mind to provide me some suggestion?
EDIT Split the line via separator
I'm assuming your input file contains each entry on one line.
In that case, replace onUploadFile with this code.
It uses Scanner to read the inputstream line by line. Do what you want with each line.
public void onUploadFile(ActionEvent actionEvent) {
if (file != null && inputstream != null) {
fileName = file.getFilename();
System.out.println("Notepad Name: " + fileName);
final Scanner scanner = new Scanner(inputstream);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//do somthing with the current line, like store each one in a list
System.out.println(line);
String[] lineElements=line.split(" ");
//16/05/2014 17:19:00 6685 00:00:31
//in your case lineElements[0] should be a date
//lineElements[1] is a timestamp linked to the before date
//lineElements[2] is a number (int)
//lineElements[3] is a timestamp
//build string from elements [0] and [1] then transform it to a date
//add logic for adding to database...
}
}
if (inputFile != null) {
inputFile.resetValue();
inputFile.setValid(true);
}
}

Categories

Resources