Search a string in entire workspace using eclipse plugin - java

I want to write a program in java to search a string in entire workspace using eclipse search plugin in my code.
I have searched for this problem but couldnt find the result.
Kindly help.
Every suggestion is appreciated.
Thanks in advance.

You do realize that there already is such a functionality in Eclipse, do you? In Eclipse Search -> File... enter your text, select *.* as the File name patterns, and workspace as Scope.
Or do you maybe want to write a plugin that uses this search internally?
From your comments I get the picture that you are looking for code to loop through directories/files and search through them. Maybe this question can help you there.

Use something like the following to recurse through all the projects and folders for file:
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
// Get all the projects in the workspace
IProject [] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
// Search each project
for (IProject project : projects)
{
searchContainer(project);
}
/*
* Search a project or folder.
*/
private void searchContainer(IContainer container)
{
// Get all the resources in the container
IResource [] members = container.members();
// Look at each resource
for (IResource member : members)
{
if (member instanceof IContainer)
{
// Resource is a folder, search that
searchContainer((IContainer)member);
}
else if (member instanceof IFile)
{
// Resource is a file, search that
searchFile((IFile)member);
}
}
}
/*
* Search a file.
*/
private void searchFile(IFile file)
{
// TODO search the file
}
You should run this in a Job or other background task as it may take some time to run.

package search_workspace09;
import java.io.*;
import java.util.regex.*;
public class workspace_search09
{
public static void main(String args[])
{
try
{
String dirName="D:/test_folder";
String stringsearch="world";
//String fileName = "test.txt";
File dir = new File(dirName);
// Open the file c:\test.txt as a buffered reader
File[] dirs=dir.listFiles();
if(dirs!=null)
{
for (int i=0;i<dirs.length;i++)
{
if(dirs[i].isFile())
{
File filename=dirs[i];
System.out.println("Files to search in " +filename);
BufferedReader bf=new BufferedReader(new FileReader(filename));
//System.out.println(filename);
// Start a line count and declare a string to hold our current line.
int countline=0;
String line;
//pattern search
Pattern p = Pattern.compile("\\b"+stringsearch+"\\b", Pattern.CASE_INSENSITIVE);
System.out.println("Search Criteria " +" Filename\t\t\t"+ " Line no. " + " Position\t" + " Line Text ");
while ( (line = bf.readLine()) != null)
{
// Increment the count and find the index of the word
countline++;
Matcher m = p.matcher(line);
// indicate all matches on the line
while(m.find())
{
System.out.println(stringsearch +"\t\t"+ filename+"\t\t" + countline + "\t " + m.start() + "\t"+line);
}
}
//continue;
}
}}}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}}}

public class workspace_search14
{
public static void main(String[] args)throws IOException
{
String dir="D:/test_folder";
File root=new File(dir);
findFiles(root,0);
}
public static void findFiles(File root,int depth) throws IOException
{
File[] listOfFiles = root.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile())
{
if (iName.endsWith(".txt") || iName.endsWith(".TXT")||iName.endsWith(".java"))
{
for (int j = 0; j < depth; j++)
System.out.print("\t");
System.out.println("\nFile_Name: "+iName);
searchFiles(listOfFiles[i]);
}
}
else if (listOfFiles[i].isDirectory())
{
for (int j = 0; j < depth; j++)
System.out.print("\t");
System.out.println("\nDirectory_Name: "+iName);
findFiles(listOfFiles[i], depth+1);
}
}
}
public static void searchFiles(File FileName)throws IOException
{
int countline=0;
String line;
String stringsearch="world";
BufferedReader bf=new BufferedReader(new FileReader(FileName));
Pattern p = Pattern.compile("\\b"+stringsearch+"\\b", Pattern.CASE_INSENSITIVE);
System.out.println("Search Criteria " +" Filename\t\t\t"+ " Line no. " + " Position\t" + " Line Text ");
while ( (line = bf.readLine()) != null)
{
countline++;
Matcher m = p.matcher(line);
while(m.find())
{
System.out.println(stringsearch +"\t\t"+ FileName+"\t\t" + countline + "\t " + m.start() + "\t"+line);
}}}}

Related

Implementing Elimination of Immediate Left-Recursion in Java

I am working on implementing a generic code to solve left recursion problem in a grammar using java so my code is working as follows I am reading an input like this as each line goes to the next line:
E
E+T|T
T
T*F|F
F
(E)|id|number
and the required output is supposed to be like this one :
E->[TE']
T->[FT']
F->[(E), id, number]
E'->[+TE', !]
T'->[*FT', !]
I wrote that code which is storing input in Arraylists to iterate over them and produce the output:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class IleftRecursion {
//storing each line in its corresponding Arraylist
static ArrayList<String> leftRules = new ArrayList<>();
static ArrayList<String> rightRules = new ArrayList<>();
public static void read_file(String file) throws IOException {
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
leftRules.add(line);
rightRules.add(br.readLine());
}
br.close();
}
public static void ss() {
for (int i = 0; i < leftRules.size(); i++) {
for (int j = 1; j <= i - 1; j++) {
//splitting inputs on bars "|" to iterate through them
for (String x : rightRules.get(i).split("\\|")) {
if (x.contains(leftRules.get(j))) {
String f = "";
String ff = "";
for (int k=0; k<rightRules.get(k).split("\\|").length;k++) {
f = x;
f = f.replaceAll(leftRules.get(i), rightRules.get(k).split("\\|")[k]);
ff += f;
}
rightRules.remove(i);
rightRules.add(i, ff);
}
}
}
//Recursive or Not boolean
boolean isRec = false;
for (String z : rightRules.get(i).split("\\|")) {
if (z.startsWith(leftRules.get(i))) {
isRec = true;
break;
}
}
if (isRec) {
String a = "";
String b = "";
for (String s : rightRules.get(i).split("\\|")) {
if (s.startsWith(leftRules.get(i))) {
b += s.replaceAll(leftRules.get(i), "") + leftRules.get(i) + "',";
} else {
a += s + leftRules.get(i) + "'";
}
}
b += "!";
if(a.length()>=1)
a.substring(1, a.length() - 1);
rightRules.add(i, a);
rightRules.add(i + 1, b);
leftRules.add(leftRules.get(i) + "'");
}
}
}
public static void main(String[] args) throws IOException {
read_file("Sample.in");
ss();
for (int i=0;i<leftRules.size();i++)
{
System.out.print(leftRules.get(i)+"->");
System.out.println("["+rightRules.get(i)+"]");
}
}
}
I debugged the code many times trying to figure out why Am I getting output like this
E->[TE']
T->[+TE',!]
F->[T]
E'->[T*F]
Which is missing One rule and also not all the new productions generated in the right way but I couldn't fix could anyone help me through that ?

How to find similar lines in two text files irrespective of the line number at which they occur

I am trying to open two text files and find similar lines in them.
My code is correctly reading all the lines from both the text files.
I have used nested for loops to compare line1 of first text file with all lines of second text file and so on.
However, it is only detecting similar lines which have same line number,
(eg. line 1 of txt1 is cc cc cc and line 1 of txt2 is cc cc cc, then it correctly finds and prints it),
but it doesn't detect same lines on different line numbers in those files.
import java.io.*;
import java.util.*;
public class FeatureSelection500 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
File f1 = new File("E://implementation1/practise/ComUpdatusPS.exe.hex-04-ngrams-Freq.txt");
File f2 = new File("E://implementation1/practise/top-300features.txt");
Scanner scan1 = new Scanner(f1);
Scanner scan2 = new Scanner(f2);
int i = 1;
List<String> txtFileOne = new ArrayList<String>();
List<String> txtFileTwo = new ArrayList<String>();
while (scan1.hasNext()) {
txtFileOne.add(scan1.nextLine());
}
while (scan2.hasNext())
{
txtFileTwo.add(scan2.nextLine());
}
/*
for(String ot : txtFileTwo )
{
for (String outPut : txtFileOne)
{
// if (txtFileTwo.contains(outPut))
if(outPut.equals(ot))
{
System.out.print(i + " ");
System.out.println(outPut);
i++;
}
}
}
*/
for (int j = 0; j < txtFileTwo.size(); j++) {
String fsl = txtFileTwo.get(j);
// System.out.println(fileContentSingleLine);
for (int z = 0; z < 600; z++) // z < txtFileOne.size()
{
String s = txtFileOne.get(z);
// System.out.println(fsl+"\t \t"+ s);
if (fsl.equals(s)) {
System.out.println(fsl + "\t \t" + s);
// my line
// System.out.println(fsl);
} else {
continue;
}
}
}
}
}
I made your code look nicer, you're welcome :)
Anyway, I don't understand that you get that bug. It runs through all of the list2 for every line in the list1...
import java.io.*;
import java.util.*;
public class FeatureSelection500 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
File file1 = new File("E://implementation1/practise/ComUpdatusPS.exe.hex-04-ngrams-Freq.txt");
File file2 = new File("E://implementation1/practise/top-300features.txt");
Scanner scan1 = new Scanner(file1);
Scanner scan2 = new Scanner(file2);
List<String> txtFile1 = new ArrayList<String>();
List<String> txtFile2 = new ArrayList<String>();
while (scan1.hasNext()) {
txtFile1.add(scan1.nextLine());
}
while (scan2.hasNext()) {
txtFile2.add(scan2.nextLine());
}
for (int i = 0; i < txtFile2.size(); i++) {
String lineI = txtFile2.get(i);
// System.out.println(fileContentSingleLine);
for (int j = 0; j < txtFile1.size(); j++){ // z < txtFileOne.size(
String lineJ = txtFile1.get(j);
// System.out.println(fsl+"\t \t"+ s);
if (lineI.equals(lineJ)) {
System.out.println(lineI + "\t \t" + lineJ);
// my line
// System.out.println(fsl);
}
}
}
}
}
I don't see any problem with your code. Even the block you commented is absolutely fine. Since, you are doing equals() you should make sure that you have same text (same case) in the two files for them to be able to satisfy the condition successfully.
for(String ot : txtFileTwo )
{
for (String outPut : txtFileOne)
{
if(outPut.equals(ot)) /* Check Here */
{
/* Please note that here i will not give you line number,
it will just tell you the number of matches in the two files */
System.out.print(i + " ");
System.out.println(outPut);
i++;
}
}
}

What is wrong in my code logically?

I am working on a code to rename number of files in java. I have a list of the files in a .txt. File in which my program retreives the name of the document and its new name. It currently does not work.. It compiles and run but it wont rename my files.
Here's my code:
public static void rename(String ol, String ne){
File oldfile =new File(ol);
File newfile =new File(ne);
int t=0;
if( oldfile.isFile() && oldfile.canRead()){
if (newfile.exists()){
t++;
ne = ne.substring(0,ne.lastIndexOf('.')) + " (" + t + ")" +
ne.substring(ne.lastIndexOf('.')) ;
rename(ol,ne);
}
if(oldfile.renameTo(newfile))
System.out.println("Rename succesful");
else
System.out.println("Rename failed" + " - " + ol + " " + ne);
}else
System.out.println("CANNOT Rename " + oldfile + " because read/write issues. Check
if File exists" );
}
public static void main(String[] args) throws IOException
{
ReadFile ren = new ReadFile("List of Founds.txt");
String r[] = ren.OpenFile();
for(int j=0; j<ReadFile.numberOfLines; j++){
String pdfOldName = r[j].substring(0,r[j].lastIndexOf('.'));
String pdfNewName = r[j].substring((r[j].lastIndexOf('.') + 4));
rename(pdfOldName, pdfNewName);
}
}
This is the 'List of founds' .txt file, the old name is on the left and the new name is on the right.
test.pdf.txt ayo1
test2.pdf.txt ayo2
test3.pdf.txt ayo3
You can use the File.html#renameTo(java.io.File) to accomplish this.
Heres a quick sample program i wrote.
hope this puts you in right direction
public class FileMain {
static int i = 1;
public static void main(String[] args) throws Exception {
File file1 = new File("D:/workspace/dir");
renamefiles(file1);
}
private static void renamefiles(File file){
File files[] = file.listFiles();
for(File tempFile :files){
if(tempFile.isDirectory()){
renamefiles(tempFile);
}else{
System.out.println(tempFile.getName());
File renameFile = new File("sample-"+(++i)+".bck");
tempFile.renameTo(renameFile);
}
}
}
}
You need a !
if (newfile.exists())
to
if (!newfile.exists())
You also need to follow conventions. And Unit Test.

when getting drive information using java

i tried the following program
import java.io.*;
class dr
{
public static void main(String args[])
{
try{
File[] roots = File.listRoots();
for (int index = 0; index < roots.length; index++)
{ //Print out each drive/partition
System.out.println(roots[index].toString());
}
}
catch(Exception e)
{
System.out.println("error " +e);
}
}
}
but in my system floppy drive is not connected
and i am getting a message like the following
" The drive is not ready for use;its door may be open,Please check drive A: and make sure that disk is inserted and that the drive door is closed"
then three options are shown cancel,try again,continue
when i try continue,it works
but how i could avoid that msg
What are you trying to do?
My recommendation would be to use FileSystemView.
It's used something like this:
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (File f: roots) {
System.out.println(fsv.getSystemDisplayName(f);
}
package com.littletutorials.fs;
import java.io.*;
import javax.swing.filechooser.*;
public class DriveTypeInfo
{
public static void main(String[] args)
{
System.out.println("File system roots returned byFileSystemView.getFileSystemView():");
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++)
{
System.out.println("Root: " + roots[i]);
}
System.out.println("Home directory: " + fsv.getHomeDirectory());
System.out.println("File system roots returned by File.listRoots():");
File[] f = File.listRoots();
for (int i = 0; i < f.length; i++)
{
System.out.println("Drive: " + f[i]);
System.out.println("Display name: " + fsv.getSystemDisplayName(f[i]));
System.out.println("Is drive: " + fsv.isDrive(f[i]));
System.out.println("Is floppy: " + fsv.isFloppyDrive(f[i]));
System.out.println("Readable: " + f[i].canRead());
System.out.println("Writable: " + f[i].canWrite());
System.out.println("Total space: " + f[i].getTotalSpace());
System.out.println("Usable space: " + f[i].getUsableSpace());
}
}
}
reference : http://littletutorials.com/2008/03/10/getting-file-system-details-in-java/
When it comes to Windows, this class WindowsAltFileSystemView proposes an alternative based on FileSystemView
This class is necessary due to an annoying bug on Windows NT where instantiating a JFileChooser with the default FileSystemView will cause a "drive A: not ready" error every time.
I grabbed the Windows FileSystemView impl from the 1.3 SDK and modified it so * as to not use java.io.File.listRoots() to get fileSystem roots.
java.io.File.listRoots() does a SecurityManager.checkRead() which causes the OS to try to access drive A: even when there is no disk, causing an annoying "abort, retry, ignore" popup message every time we instantiate a JFileChooser!
So here, the idea is to extends FileSystemView, replacing the getRoots() method with:
/**
* Returns all root partitians on this system. On Windows, this
* will be the A: through Z: drives.
*/
public File[] getRoots() {
Vector rootsVector = new Vector();
// Create the A: drive whether it is mounted or not
FileSystemRoot floppy = new FileSystemRoot("A" + ":" + "\\");
rootsVector.addElement(floppy);
// Run through all possible mount points and check
// for their existance.
for (char c = 'C'; c <= 'Z'; c++) {
char device[] = {c, ':', '\\'};
String deviceName = new String(device);
File deviceFile = new FileSystemRoot(deviceName);
if (deviceFile != null && deviceFile.exists()) {
rootsVector.addElement(deviceFile);
}
}
File[] roots = new File[rootsVector.size()];
rootsVector.copyInto(roots);
return roots;
}
you can use this;
import java.io.File;
class dr
{
public static void main(String args[])
{
File[] roots=File.listRoots();
for(File root:roots)
{
System.out.println(root.getName());
}
}
}

How to discover a File's creation time with Java?

Is there an easy way to discover a File's creation time with Java? The File class only has a method to get the "last modified" time. According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.
The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time. I guess this works, I only need to support Windows, but it seems very error prone to me.
Are there any third party libraries that provide the info I need?
Update: In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a good choice for anyone else that has this problem.
With the release of Java 7 there is a built-in way to do this:
Path path = Paths.get("path/to/file");
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
FileTime creationTime = attributes.creationTime();
It is important to note that not all operating systems provide this information. I believe in those instances this returns the mtime which is the last modified time.
Windows does provide creation time.
I've wrote a small test class some days ago, wish it can help you:
// Get/Set windows file CreationTime/LastWriteTime/LastAccessTime
// Test with jna-3.2.7
// [http://maclife.net/wiki/index.php?title=Java_get_and_set_windows_system_file_creation_time_via_JNA_(Java_Native_Access)][1]
import java.io.*;
import java.nio.*;
import java.util.Date;
// Java Native Access library: jna.dev.java.net
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import com.sun.jna.win32.*;
import com.sun.jna.platform.win32.*;
public class WindowsFileTime
{
public static final int GENERIC_READ = 0x80000000;
//public static final int GENERIC_WRITE = 0x40000000; // defined in com.sun.jna.platform.win32.WinNT
public static final int GENERIC_EXECUTE = 0x20000000;
public static final int GENERIC_ALL = 0x10000000;
// defined in com.sun.jna.platform.win32.WinNT
//public static final int CREATE_NEW = 1;
//public static final int CREATE_ALWAYS = 2;
//public static final int OPEN_EXISTING = 3;
//public static final int OPEN_ALWAYS = 4;
//public static final int TRUNCATE_EXISTING = 5;
public interface MoreKernel32 extends Kernel32
{
static final MoreKernel32 instance = (MoreKernel32)Native.loadLibrary ("kernel32", MoreKernel32.class, W32APIOptions.DEFAULT_OPTIONS);
boolean GetFileTime (WinNT.HANDLE hFile, WinBase.FILETIME lpCreationTime, WinBase.FILETIME lpLastAccessTime, WinBase.FILETIME lpLastWriteTime);
boolean SetFileTime (WinNT.HANDLE hFile, final WinBase.FILETIME lpCreationTime, final WinBase.FILETIME lpLastAccessTime, final WinBase.FILETIME lpLastWriteTime);
}
static MoreKernel32 win32 = MoreKernel32.instance;
//static Kernel32 _win32 = (Kernel32)win32;
static WinBase.FILETIME _creationTime = new WinBase.FILETIME ();
static WinBase.FILETIME _lastWriteTime = new WinBase.FILETIME ();
static WinBase.FILETIME _lastAccessTime = new WinBase.FILETIME ();
static boolean GetFileTime (String sFileName, Date creationTime, Date lastWriteTime, Date lastAccessTime)
{
WinNT.HANDLE hFile = OpenFile (sFileName, GENERIC_READ); // may be WinNT.GENERIC_READ in future jna version.
if (hFile == WinBase.INVALID_HANDLE_VALUE) return false;
boolean rc = win32.GetFileTime (hFile, _creationTime, _lastAccessTime, _lastWriteTime);
if (rc)
{
if (creationTime != null) creationTime.setTime (_creationTime.toLong());
if (lastAccessTime != null) lastAccessTime.setTime (_lastAccessTime.toLong());
if (lastWriteTime != null) lastWriteTime.setTime (_lastWriteTime.toLong());
}
else
{
int iLastError = win32.GetLastError();
System.out.print ("获取文件时间失败,错误码:" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError));
}
win32.CloseHandle (hFile);
return rc;
}
static boolean SetFileTime (String sFileName, final Date creationTime, final Date lastWriteTime, final Date lastAccessTime)
{
WinNT.HANDLE hFile = OpenFile (sFileName, WinNT.GENERIC_WRITE);
if (hFile == WinBase.INVALID_HANDLE_VALUE) return false;
ConvertDateToFILETIME (creationTime, _creationTime);
ConvertDateToFILETIME (lastWriteTime, _lastWriteTime);
ConvertDateToFILETIME (lastAccessTime, _lastAccessTime);
//System.out.println ("creationTime: " + creationTime);
//System.out.println ("lastWriteTime: " + lastWriteTime);
//System.out.println ("lastAccessTime: " + lastAccessTime);
//System.out.println ("_creationTime: " + _creationTime);
//System.out.println ("_lastWriteTime: " + _lastWriteTime);
//System.out.println ("_lastAccessTime: " + _lastAccessTime);
boolean rc = win32.SetFileTime (hFile, creationTime==null?null:_creationTime, lastAccessTime==null?null:_lastAccessTime, lastWriteTime==null?null:_lastWriteTime);
if (! rc)
{
int iLastError = win32.GetLastError();
System.out.print ("设置文件时间失败,错误码:" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError));
}
win32.CloseHandle (hFile);
return rc;
}
static void ConvertDateToFILETIME (Date date, WinBase.FILETIME ft)
{
if (ft != null)
{
long iFileTime = 0;
if (date != null)
{
iFileTime = WinBase.FILETIME.dateToFileTime (date);
ft.dwHighDateTime = (int)((iFileTime >> 32) & 0xFFFFFFFFL);
ft.dwLowDateTime = (int)(iFileTime & 0xFFFFFFFFL);
}
else
{
ft.dwHighDateTime = 0;
ft.dwLowDateTime = 0;
}
}
}
static WinNT.HANDLE OpenFile (String sFileName, int dwDesiredAccess)
{
WinNT.HANDLE hFile = win32.CreateFile (
sFileName,
dwDesiredAccess,
0,
null,
WinNT.OPEN_EXISTING,
0,
null
);
if (hFile == WinBase.INVALID_HANDLE_VALUE)
{
int iLastError = win32.GetLastError();
System.out.print (" 打开文件失败,错误码:" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError));
}
return hFile;
}
static String GetWindowsSystemErrorMessage (int iError)
{
char[] buf = new char[255];
CharBuffer bb = CharBuffer.wrap (buf);
//bb.clear ();
//PointerByReference pMsgBuf = new PointerByReference ();
int iChar = win32.FormatMessage (
WinBase.FORMAT_MESSAGE_FROM_SYSTEM
//| WinBase.FORMAT_MESSAGE_IGNORE_INSERTS
//|WinBase.FORMAT_MESSAGE_ALLOCATE_BUFFER
,
null,
iError,
0x0804,
bb, buf.length,
//pMsgBuf, 0,
null
);
//for (int i=0; i<iChar; i++)
//{
// System.out.print (" ");
// System.out.print (String.format("%02X", buf[i]&0xFFFF));
//}
bb.limit (iChar);
//System.out.print (bb);
//System.out.print (pMsgBuf.getValue().getString(0));
//win32.LocalFree (pMsgBuf.getValue());
return bb.toString ();
}
public static void main (String[] args) throws Exception
{
if (args.length == 0)
{
System.out.println ("获取 Windows 的文件时间(创建时间、最后修改时间、最后访问时间)");
System.out.println ("用法:");
System.out.println (" java -cp .;..;jna.jar;platform.jar WindowsFileTime [文件名1] [文件名2]...");
return;
}
boolean rc;
java.sql.Timestamp ct = new java.sql.Timestamp(0);
java.sql.Timestamp wt = new java.sql.Timestamp(0);
java.sql.Timestamp at = new java.sql.Timestamp(0);
for (String sFileName : args)
{
System.out.println ("文件 " + sFileName);
rc = GetFileTime (sFileName, ct, wt, at);
if (rc)
{
System.out.println (" 创建时间:" + ct);
System.out.println (" 修改时间:" + wt);
System.out.println (" 访问时间:" + at);
}
else
{
//System.out.println ("GetFileTime 失败");
}
//wt.setTime (System.currentTimeMillis());
wt = java.sql.Timestamp.valueOf("2010-07-23 00:00:00");
rc = SetFileTime (sFileName, null, wt, null);
if (rc)
{
System.out.println ("SetFileTime (最后修改时间) 成功");
}
else
{
//System.out.println ("SetFileTime 失败");
}
}
}
}
I've been investigating this myself, but I need something that will work across Windows/*nix platforms.
One SO post includes some links to Posix JNI implementations.
JNA-POSIX
POSIX for Java
In particular, JNA-POSIX implements methods for getting file stats with implementations for Windows, BSD, Solaris, Linux and OSX.
All in all it looks very promising, so I'll be trying it out on my own project very soon.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CreateDateInJava {
public static void main(String args[]) {
try {
// get runtime environment and execute child process
Runtime systemShell = Runtime.getRuntime();
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter filename: ");
String fname = (String) br1.readLine();
Process output = systemShell.exec("cmd /c dir \"" + fname + "\" /tc");
System.out.println(output);
// open reader to get output from process
BufferedReader br = new BufferedReader(new InputStreamReader(output.getInputStream()));
String out = "";
String line = null;
int step = 1;
while ((line = br.readLine()) != null) {
if (step == 6) {
out = line;
}
step++;
}
// display process output
try {
out = out.replaceAll(" ", "");
System.out.println("CreationDate: " + out.substring(0, 10));
System.out.println("CreationTime: " + out.substring(10, 16) + "m");
} catch (StringIndexOutOfBoundsException se) {
System.out.println("File not found");
}
} catch (IOException ioe) {
System.err.println(ioe);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
/**
D:\Foldername\Filename.Extension
Ex:
Enter Filename :
D:\Kamal\Test.txt
CreationDate: 02/14/2011
CreationTime: 12:59Pm
*/
The javaxt-core library includes a File class that can be used to retrieve file attributes, including the creation time. Example:
javaxt.io.File file = new javaxt.io.File("/temp/file.txt");
System.out.println("Created: " + file.getCreationTime());
System.out.println("Accessed: " + file.getLastAccessTime());
System.out.println("Modified: " + file.getLastModifiedTime());
Works with Java 1.5 and up.
I like the answer on jGuru that lists the option of using JNI to get the answer. This might prove to be faster than shelling out and you may encounter other situations such as this that need to be implemented specifically for windows.
Also, if you ever need to port to a different platform, then you can port your library as well and just have it return -1 for the answer to this question on *ix.
This is a basic example in Java, using BasicFileAttributes class:
Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt");
BasicFileAttributes attr;
try {
attr = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("File creation time: " + attr.creationTime());
} catch (IOException e) {
System.out.println("oops un error! " + e.getMessage());
}

Categories

Resources