In my spring-batch-integration app, file polling invokes the batchjob for eachfile and this application could be running on multiple servers(nodes) but they all are supposed to read a common directory.Now, I wrote a custom locker which takes the lock on file so that any other instance will not be able to process the same file . code as below
public class MyFileLocker extends AbstractFileLockerFilter{
private final ConcurrentMap<File, FileLock> lockCache = new ConcurrentHashMap<File, FileLock>();
private final ConcurrentMap<File, FileChannel> ChannelCache = new ConcurrentHashMap<File, FileChannel>();
#Override
public boolean lock(File fileToLock) {
FileChannel channel;
FileLock lock;
try {
channel = new RandomAccessFile(fileToLock, "rw").getChannel();
lock = channel.tryLock();
if (lock == null || !lock.isValid()) {
System.out.println(" Problem in acquiring lock!!" + fileToLock);
return false;
}
lockCache.put(fileToLock, lock);
ChannelCache.put(fileToLock, channel);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
public boolean isLockable(File file) {
return file.canWrite();
}
#Override
public void unlock(File fileToUnlock) {
FileLock lock = lockCache.get(fileToUnlock);
try {
if(lock!=null){
lock.release();
ChannelCache.get(fileToUnlock).close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now, when i invoke my Spring batch and i try to read that file using flatfileitemreader it gives me
org.springframework.batch.item.file.NonTransientFlatFileException
which i believe is coming beacuse file is locked. I did some googling and found that NIOLocker locks the file in a way that even the current thread can't read it. I found a link where it shows how to read the locked file but they are using buffer.
How can I make my file accessible to my FlatfileItemReader.
Please suggest.
Yes, you really can get access to the locked file content only over ByteBuffer:
FileChannel fileChannel = channelCache.get(lockedFile);
ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size());
fileChannel.read(byteBuffer);
System.out.println("Read File " + lockedFile.getName() + " with content: " + new String(byteBuffer.array()));
Oh! Yeah. You really pointed to my repo :-).
So, with locker you don't have choice unless copy/paste the file byte[] that way before FlatfileItemReader or just inject some custom BufferedReaderFactory into the same FlatfileItemReader, which converts the locked file to the appropriate BufferedReader:
new BufferedReader(new CharArrayReader(byteBuffer.asCharBuffer().array()));
Based on the link that you shared, looks like you could try the following.
//This is from your link (except the size variable)
FileChannel fileChannel = channelCache.get(lockedFile);
int size = (int) fileChannel.size();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
fileChannel.read(byteBuffer);
//Additional code that you could try
byte[] bArray = new byte[size];
//Write data to the byte array
byteBuffer.get(bArray);
FlatFileItemReader flatFileItemReader = new FlatFileItemReader();
flatFileItemReader.setResource(new ByteArrayResource(bArray));
//Next you can try reading from your flatFileItemReader as usual
...
Let me know if it doesn't progress your issue.
Solution : I am creating a temporary file with content of the locked file and processing it. Once processing is done i archive that file and remove the locked and temporary both files. Key here is to create a new file with locked file content. code for below is as follows :
File tmpFile = new File(inputFile.getAbsolutePath() + ".lck");
FileChannel fileChannel = MyFileLocker.getChannelCache().get(new File(inputFile.getAbsolutePath()));
InputStream inputStream = Channels.newInputStream(fileChannel);
ByteStreams.copy(inputStream, Files.newOutputStreamSupplier(tmpFile));
Here inputFile is my locked file and tmp file is new file with locked file content. I have also created a method in my locker class to unlock and delete
public void unlockAndDelete(File fileToUnlockandDelete) {
FileLock lock = lockCache.get(fileToUnlockandDelete);
String fileName = fileToUnlockandDelete.getName();
try {
if(lock!=null){
lock.release();
channelCache.get(fileToUnlockandDelete).close();
//remove from cache
lockCache.remove(fileToUnlockandDelete);
channelCache.remove(fileToUnlockandDelete);
boolean isFiledeleted = fileToUnlockandDelete.delete();
if(isFiledeleted){
System.out.println("File deleted successfully" + fileName);
}else{
System.out.println("File is not deleted."+fileName);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
I am reading a file using RandomFileAccess, FileChannel and ByteBuffer as follows:
RandomAccessFile myFile = new RandomAccessFile("/Users/****/Documents/a.txt", "rw");
FileChannel myInChannel = myFile.getChannel();
ByteBuffer bb = ByteBuffer.allocate(48);
int bytesRead = myInChannel.read(bb);
while (bytesRead != -1) {
// do something
}
myFile.close();
All this code is working fine.
But i am wondering is there any way i can read the data using Future?
I tried following code, and it worked fine for:
try(AsynchronousFileChannel afileChannel = AsynchronousFileChannel.open(Paths.get("/Users/***/Documents/myFile.txt"), StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
Future<Integer> operation = afileChannel.read(buffer, position);
while(!operation.isDone()){
//do something
}
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println(new String(data));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Got to know that this can be done via AsynchronousFileChannel but not via FileChannel.
I'm trying to Open the CMD Using java + Applying code to it to open an .jar so the applications output is shown in the .bat file.
can someone tell me how to do it?
This is the code it got,it does run excecute the file but the CMD doesnt show.
btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String Bat = "C:"+File.separatorChar+"Users"+File.separatorChar+"Gebruiker"+File.separatorChar+"AppData"+File.separatorChar+"Local"+File.separatorChar+"Temp"+File.separatorChar+"hexT"+File.separatorChar+"run.bat";
Runtime rt = Runtime.getRuntime();
try {
rt.exec(Bat);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Edited: This works for me:
String Bat = "C:\\app.bat"; //Try to use \\ as path seperator
try {
Runtime.getRuntime().exec("cmd /c start " + Bat);
} catch (IOException e) {
e.printStackTrace();
}
Define this :
FileWriter writer;
then in your try/catch do the following :
try {
writer = new FileWriter("test.txt");
Process child = rt.exec(Bat);
InputStream input = child.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
BufferedReader commandResult = new BufferedReader(new InputStreamReader(buffer));
String line = "";
try {
while ((line = commandResult.readLine()) != null) {
writer.write(line + "\n");
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This will read the output as a buffer line by line and write it into a text file
I searched around for this but I could not find a soultion.
Sorry about my bad description. Im not very good at this.
I have a UI class
Its calling a "lotto" class.
That lotto classes constructor is called a method named readData()
readData is reading from a file using BufferedReader
Im not getting an error message but its just not reading.
It gets stuck at BufferedReader fr = new BufferedReader... and goes to the catch thing.
If its a file not found problem how would i make it track where my file is. Im using eclipse and the program is stored on my usb. I need to hand it in to my teacher so i cant just put a location in. Is there code that tracks where my program is then takes the file from that folder?
Here is the code being used.
import java.io.*;
//contructor
public Lotto()
{
try
{
readData();
nc = new NumberChecker();
}
catch(IOException e)
{
System.out.println("There was a problem");
}
}
private void readData() throws IOException
{
//this method reads winning tickets date and pot from a file
BufferedReader file = new BufferedReader (new FileReader("data.txt"));
for(int i=0;i<5;i++)
{
System.out.println("in "+i);
winningNums[i] = file.readLine();
winningDates[i] = file.readLine();
weeksMoney[i] = Integer.parseInt(file.readLine());
System.out.println("out "+i);
}
file.close();
}
if you get an error in this line of code
BufferedReader file = new BufferedReader (new FileReader("data.txt"));
Then it is probably a FileNotFoundException
Make sure that the data.txt file is in the same folder as your compiled .class file and not the .java source.
It would be best to use a proper root to your file ex. c:\my\path\data.txt
And don't forget the \
Try surrounding the BufferedReader in a try catch and look for a file not found exception as well as IO exception. Also try putting in the fully qualified path name with double backslashes.
BufferedReader file;
try {
file = new BufferedReader (new FileReader("C:\\filepath\\data.txt"));
for(int i=0;i<5;i++)
{
System.out.println("in "+i);
winningNums[i] = file.readLine();
winningDates[i] = file.readLine();
weeksMoney[i] = Integer.parseInt(file.readLine());
System.out.println("out "+i);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have researched and tried to refer back to my fileChooser.getSeletedFile() in my save as action but can not work out how to check whether or not a file has been created. Here is my attempted code so far:
Save as code(works well):
public void Save_As() {
fileChooserTest.setApproveButtonText("Save");
int actionDialog = fileChooserTest.showOpenDialog(this);
File fileName = new File(fileChooserTest.getSelectedFile() + ".txt");
try {
if (fileName == null) {
return;
}
BufferedWriter outFile = new BufferedWriter(new FileWriter(fileName));
outFile.write(this.jTextArea2.getText());//put in textfile
outFile.flush(); // redundant, done by close()
outFile.close();
} catch (IOException ex) {
}
}
"Save" code doesn't work:
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
File f = fileChooserTest.getSelectedFile();
try {
if (f.exists()) {
BufferedWriter bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
String text = ((JTextArea) jTabbedPane1.getSelectedComponent()).getText();
bw1.write(text);
bw1.close();
} else {
Save_As();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Instead of storing an instance to the JFileChooser rather store an instance to the File (wich will be null before any save has been performed). In your SaveActionPerformed method check if the file is null. If it is null then do a Save_As and store the selected file in your file variable, if it is not null then do a normal save into the file.
I want to get the XML in atom format of a GoogleDocs spreadsheet using the [generateAtom(..,..)][1] method of the class BaseEntry which a SpreadsheetEntry inherits. But I don't understand the the second parameter in the method, ExtensionProfile. What is it and will this method call suffice if I just want to get the XML in atom format?
XmlWriter x = new XmlWriter();
spreadSheetEntry.generateAtom(x,new ExtensionProfile());
[1]: http://code.google.com/apis/gdata/javadoc/com/google/gdata/data/BaseEntry.html#generateAtom(com.google.gdata.util.common.xml.XmlWriter, com.google.gdata.data.ExtensionProfile)
From the JavaDoc for ExtensionProfile:
A profile is a set of allowed
extensions for each type together with
additional properties.
Usually if you've got a service, you can ask that for its extension profile using Service.getExtensionProfile().
Elaborating Jon Skeet's answer, you need to instanciate a service like this:
String developer_key = "mySecretDeveloperKey";
String client_id = "myApplicationsClientId";
YouTubeService service = new YouTubeService(client_id, developer_key);
Then you can write to a file using the extension profile of your service:
static void write_video_entry(VideoEntry video_entry) {
try {
String cache_file_path = Layout.get_cache_file_path(video_entry);
File cache_file = new File(cache_file_path);
Writer writer = new FileWriter(cache_file);
XmlWriter xml_writer = new XmlWriter(writer);
ExtensionProfile extension_profile = service.getExtensionProfile();
video_entry.generateAtom(xml_writer, extension_profile);
xml_writer.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Analogously, you can read a file using the extension profile of your service:
static VideoFeed read_video_feed(File cache_file_file) {
VideoFeed video_feed = new VideoFeed();
try {
InputStream input_stream = new FileInputStream(cache_file_file);
ExtensionProfile extension_profile = service.getExtensionProfile();
try {
video_feed.parseAtom(extension_profile, input_stream);
} catch (ParseException e) {
e.printStackTrace();
}
input_stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return video_feed;
}