I'm trying to lock file exclusively on read - java

I'm trying to lock a file exclusively on read.
I am using Java 7 on Windows 7.
The files are copied to a directory, and then I want to to read them correctly after copy. That's why I'm trying lock file exclusively on read.
But my program read file in the middle.
Can anyone please help me with this? Thanks!
package test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
public class FileLockMove {
public static void main(String[] args) {
FileSystem fs = FileSystems.getDefault();
File dir = new File("c:/test_source/");
while(true){
for (File file : dir.listFiles()) {
try (FileChannel fc = (new RandomAccessFile(file, "rw")).getChannel()){
FileLock lock = fc.tryLock();
if(lock != null){
System.out.println("lock is not null\t" + file.getName());
System.out.println("addBody: " + file.getAbsolutePath() + "\t" + file.length());
}else{
System.out.println("lock is null\t" + file.getName());
continue;
}
} catch (Exception e) {
System.out.println("fail:" + file.getName()+"\t" + e.getMessage());
}
try {
Files.move(file.toPath(), fs.getPath("c:/test_dest/",file.getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Originally, the copy file is not Java, but I created a copy of my program slowly to confirm that I can lock exclusively.
package test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
public class FileCopySlow{
public static void main(String[] args) {
String source = "C:/test_orig/";
String dst ="C:/test_source/";
File file = new File(source);
File[] files = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
if(name.matches(".*\\.bmp")){
return true;
}
return false;
}
});
for(File f: files){
copyStream(f, dst);
}
}
static void copyStream(File source,String dst){
try(BufferedInputStream br = new BufferedInputStream(new FileInputStream(source))){
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dst+source.getName()));
byte[] buff = new byte[100];
int len = -1;
while((len = br.read(buff)) >-1){
out.write(buff,0,len);
out.flush();
Thread.sleep(100);
}
out.close();
System.out.println(source.getName() + "\tfinish");
}catch(Exception e){
e.printStackTrace();
}
}
}

Related

Can i take a screenshot and paste it in a word file in appium using Java?

I'm currently using the below method to take screenshots and store them in a folder called 'Screenshots'. But what i want is, to take these screenshots and paste them in a word document according to the test cases to which they belong.
Is it possible? If so could somebody please guide me?
public String FailureScreenshotAndroid(String name) {
try {
Date d = new Date();
String date = d.toString().replace(":", "_").replace(" ", "_");
TakesScreenshot t = (TakesScreenshot)driver;
File f1 = t.getScreenshotAs(OutputType.FILE);//Temporary Location
String permanentLocation =System.getProperty("user.dir")+ "\\Screenshots\\"+name+date+".png";
File f2 = new File(permanentLocation);
FileUtils.copyFile(f1, f2);
return permanentLocation;
}catch (Exception e) {
String msg = e.getMessage();
return msg;
}
}
Try below:
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class TakeScreenshots {
public static void main(String[] args) {
try {
XWPFDocument docx = new XWPFDocument();
XWPFRun run = docx.createParagraph().createRun();
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
for (int counter = 1; counter <= 5; counter++) {
captureScreenShot(docx, run, out);
TimeUnit.SECONDS.sleep(1);
}
docx.write(out);
out.flush();
out.close();
docx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void captureScreenShot(XWPFDocument docx, XWPFRun run, FileOutputStream out) throws Exception {
String screenshot_name = System.currentTimeMillis() + ".png";
BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
File file = new File("d:/xyz/" + screenshot_name);
ImageIO.write(image, "png", file);
InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
run.addBreak();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
pic.close();
file.delete();
}
}

Java application not completing

Was trying to get a JFrame added to see if it would help with using launch4j to convert a small jar file to an .exe. I wrote a short program to help sort HPLC data at work and want to make it just a simple point and click.
It works when I run it from the command line java KFile and the JFileChooser lets me choose directories for the script to work on. When I converted it to the .exe, the JFileChooser never rendered and the .exe closes.
I read that I might need a JFrame parent and so I created a JFrame, but now the script hangs before completion as if waiting for the frame to close. I'm pretty new to java, so I'm not sure how I to resolve this issue.
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.FileVisitResult;
import java.nio.MappedByteBuffer;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import java.util.Collection;
import java.util.ArrayList;
import java.nio.file.SimpleFileVisitor;
public class KFile extends SimpleFileVisitor<Path> {
public static void main(String[] args) {
Path currPath = Paths.get("");
String currDir = currPath.toAbsolutePath().toString();
System.out.println(currDir);
File dataDir = chooseDir("open");
File destDir = chooseDir("save");
if(!destDir.exists()) {
try {
destDir.mkdir();
}
catch (SecurityException se) {
System.out.println("Couldn't make directory!");
}
}
int n = 0;
if(dataDir.exists()) {
Collection<Path> allDir = new ArrayList<Path>();
try {
addTree(dataDir.toPath(),allDir);
}
catch (IOException e) {
System.out.println("Error with scanning");
}
for( Path thisPath : allDir ) {
if(thisPath.toString().contains("Report.pdf")) {
Path thisDir = thisPath.getParent();
File f = new File(thisDir.toString(), "\\Report.txt");
n = n + 1;
String fileName = "Report " + n + ".pdf";
try {
fileName = parseName(f);
System.out.println(fileName);
} catch (IOException e) {
e.printStackTrace();
}
File thisFile = new File(destDir + "\\" + fileName);
try {
copyFile(thisPath.toFile(),thisFile);
} catch ( IOException e) {
e.printStackTrace();
}
}
}
}
}
public static boolean copyFile(File sourceFile, File destFile) throws IOException {
//create file if it doesn't exist.
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
return true;
}
return false;
}
}
public static File chooseDir(String s) {
JFrame myFrame = new JFrame("HPLC Data Transfer");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
JFileChooser chooser = new JFileChooser();
File currDir = new File(System.getProperty("user.home") + "\\Documents");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setCurrentDirectory(currDir);
int choice = 0;
if (s.equals("save")) {
choice = chooser.showSaveDialog(myFrame);
} else {
choice = chooser.showOpenDialog(myFrame);
}
myFrame.setVisible(false);
myFrame.removeAll();
if(choice == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open: " + chooser.getSelectedFile().getName());
return chooser.getSelectedFile();
}
return new File("");
}
static String parseName(File f) throws IOException {
BufferedReader textReader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
int lnCnt = 32;
String[] fileData = new String[lnCnt];
for (int i = 0; i < lnCnt; i++) {
fileData[i] = textReader.readLine();
}
fileData[1] = fileData[1].replace("\uFEFF","");
String name = fileData[1].substring(13) + ".pdf";
textReader.close();
return name;
}
static void addTree(Path directory, final Collection<Path> all)
throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
all.add(file);
return FileVisitResult.CONTINUE;
}
});
}
}
You could try changing
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
and then call
myFrame.dispose();
to terminate the JFrame.
Since javadocs says EXIT_ON_CLOSE terminates the whole program using System.exit(); I'm not sure if that's the problem that is stopping your application but I hope it helps :)
It looks like you just called setVisible(false) when dealing with your JFrame. That just hides your JFrame, it doesn't get rid of it. If you want to get rid of your frame entirely (and all of its resources), call myFrame.dispose();

Invalid outout when writing to file with java

I'm trying to write the output to a csv file but the first values are in this format
I used ObjectOutputStream. Normally the first values should be 1,1,1,2,2,2,3....
Here is my code any ideas please ?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
public class ItemRecommend {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("data/test.csv");
ObjectOutputStream oos = new ObjectOutputStream(fos);
try {
DataModel dm = new FileDataModel(new File("data/rated.csv"));
ItemSimilarity sim = new LogLikelihoodSimilarity(dm);
GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dm, sim);
for (LongPrimitiveIterator items = dm.getItemIDs(); items.hasNext();){
long itemID = (int)(long) items.nextLong();
List<RecommendedItem>recommendations = recommender.mostSimilarItems(itemID, 3);
for(RecommendedItem recommendation : recommendations){
oos.writeObject(itemID + "," + recommendation.getItemID() + "," + recommendation.getValue()+"\n");
//System.out.println(itemID + "," + recommendation.getItemID() + "," + recommendation.getValue());
}
}
} catch (IOException e) {
System.out.println("Error !");
e.printStackTrace();
} catch (TasteException e) {
System.out.println("Taste exception !");
e.printStackTrace();
}
finally {
oos.flush();
oos.close();
}
}
}
You should try FileWriter or PrintWriter
http://www.journaldev.com/878/how-to-write-a-file-in-java-using-filewriter-bufferedwriter-files-and-fileoutputstream

How to read file in ideone in java

I want to open, read, and edit file from my desktop. I am using Ideone online compiler. How do I read the file? I tried the following code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
class demo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
File file = new File("C:/Users/psanghavi/Desktop/admin_confirmation_original.txt");
if (!file.exists())
{
System.out.println("does not exist.");
return;
}
if (!(file.isFile() && file.canRead()))
{
System.out.println(file.getName() + " cannot be read from.");
return;
}
try
{
FileInputStream fis = new FileInputStream(file);
char current;
while (fis.available() > 0)
{
current = (char) fis.read();
System.out.print(current);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
My desktop has file named: admin_confirmation_original.txt
Currently, No. About the limit, Idebone FAQ say about this:
Can I write or read files in my program? - No
Can I access the network from my program? - No
You can learn more about many Ideone restricted rule at FAQ.
Ideoone doesn't support reading local files.
This is not an answer to your question, but wrt to the comments
if you want to read files hosted, you could access them using URL class.
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Demo {
public static void main(String[] args) throws IOException {
try {
final URL url = new URL("http://www.google.co.in/robots.txt");
//URL url = new URL("http://74.125.236.52/robots.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while (in.readLine() != null) {
str = in.readLine();
System.out.println(str);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
I have not tried it on file hosting sites.There are a lot of free file hostings available just google it.

see the content of a .bson file using java

I have a very large .bson file.
Now I have two question:
How can I see the content of that file? (I know it can do with "bsondump", but this command is slow, specialy for large database) (In fact I want to see the structure of that file)
How can I see the content of that file using java?
You can easily read/parse a bson file in Java using a BSONDecoder instance such as BasicBSONDecoder or DefaultBSONDecoder. These classes are included in mongo-java-driver.
Here's a simple example of a Java implementation of bsondump.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.bson.BSONDecoder;
import org.bson.BSONObject;
import org.bson.BasicBSONDecoder;
public class BsonDump {
public void bsonDump(String filename) throws FileNotFoundException {
File file = new File(filename);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BSONDecoder decoder = new BasicBSONDecoder();
int count = 0;
try {
while (inputStream.available() > 0) {
BSONObject obj = decoder.readObject(inputStream);
if(obj == null){
break;
}
System.out.println(obj);
count++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
}
}
System.err.println(String.format("%s objects read", count));
}
public static void main(String args[]) throws Exception {
if (args.length < 1) {
//TODO usage
throw new IllegalArgumentException("Expected <bson filename> argument");
}
String filename = args[0];
BsonDump bsonDump = new BsonDump();
bsonDump.bsonDump(filename);
}
}

Categories

Resources