I'm writing a program, and the have to select an excel file, that will be read by the program. My question is now, how can I prove, if the file is an excel file or not?.
The file is selected in this method:
JButton btnFile = new JButton("Select Excel File");
btnFile.setPreferredSize(new Dimension(40, 40));
btnFile.addActionListener(new ActionListener() {
// Handle open button action.
public void actionPerformed(ActionEvent e) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
// This is where a real application would open the file.
System.out.println("File: " + file.getName() + ".");
} else {
System.out.println("Open command cancelled by user.");
}
System.out.println(returnVal);
}
});
MimetypesFileTypeMap.getContentType(String) [JDK 6]
The class MimetypesFileTypeMap was introduced with Java SE 6 to provide "data typing of files via their file extension" using "the .mime.types format." The class's Javadoc explains where in a given system the class looks for MIME types file entries. My example uses the ones that come out-of-the-box with my JDK 8 installation. The next code listing demonstrates use of javax.activation.MimetypesFileTypeMap.
public String identifyFileTypeUsingMimetypesFileTypeMap(final String fileName)
{
final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
return fileTypeMap.getContentType(fileName);
}
Files.probeContentType(Path) [JDK 7]
Java SE 7 introduced the highly utilitarian Files class and that class's Javadoc succinctly describes its use: "This class consists exclusively of static methods that operate on files, directories, or other types of files" and, "in most cases, the methods defined here will delegate to the associated file system provider to perform the file operations."
The java.nio.file.Files class provides the method probeContentType(Path) that "probes the content type of a file" through use of "the installed FileTypeDetector implementations" (the Javadoc also notes that "a given invocation of the Java virtual machine maintains a system-wide list of file type detectors").
public String identifyFileTypeUsingFilesProbeContentType(final String fileName)
{
String fileType = "Undetermined";
final File file = new File(fileName);
try
{
fileType = Files.probeContentType(file.toPath());
}
catch (IOException ioException)
{
out.println(
"ERROR: Unable to determine file type for " + fileName
+ " due to exception " + ioException);
}
return fileType;
}
For more details please visit this link
Check for the file extension 'xlsx' in the file name. However, to validate whether the selected file is actually an excel file,you need a library to validate such as Apache POI HSSF. Refer this answer for more information.
You can use Apache Commons Api to check the file extension
String filename = file.getName();
if(!FilenameUtils.isExtension(filename,"xls")){
JOptionPane.showMessageDialog(null, "Choose an excel file!");
}
http://commons.apache.org/io/api-release/index.html?org/apache/commons/io/package-summary.html
You can also do something Like this.You will have to check for all the file types you are considering.I am just providing you the direction in which you should think :
String filename = file.getName();
String extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
String excel = "xls";
if (!extension.equals(excel)){
JOptionPane.showMessageDialog(null, "Choose an excel file!");
}
else {
String filepath = file.getAbsolutePath();
JOptionPane.showMessageDialog(null, filepath);
String upload = UploadPoData.initialize(null, filepath);
if ("OK".equals(upload)) {
JOptionPane.showMessageDialog(null,"Upload Successful!");
}
}
I agree with K139 and UUIIUI answers but just for information you can use as well a framework like tika for this kind of control.
You can add a filter to the filechooser that only makes it possible to chose .xlsx files (you can add more extensions by using OR in the return with another extension)
fc = new JFileChooser();
fc.setFileFilter(new FileFilter() {
public String getDescription() {
return "Excel Documents (.xlsx)";
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
} else {
String filename = f.getName().toLowerCase();
return filename.endsWith(".xlsx") ;
}
}
});
Related
I'm creating a program which will create files with different extensions. For that, i'm using the JFileChooser. I've set the FileFilter to accept only my desired extensions, but when I select one, I still have to add the extension in the name of the file myself. How can I solve that? Many thanks!
You basically have to add the extension yourself after the user closes the dialog.
This example allows the user to specify a file ending with ".foo" or ".bar" and will add that extension if the user did not do so.
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
fileChooser.setFileFilter(new FileNameExtensionFilter("Files ending in .foo", "foo"));
fileChooser.setFileFilter(new FileNameExtensionFilter("Files ending in .bar", "bar"));
int option = fileChooser.showSaveDialog(null);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file!=null) {
FileFilter fileFilter = fileChooser.getFileFilter();
if (fileFilter instanceof FileNameExtensionFilter && ! fileFilter.accept(file)) {
// if the filter doesn't accept the filename, that must be because it doesn't have the correct extension
// so change the extension to the first extension offered by the filter.
FileNameExtensionFilter fileNameExtensionFilter = (FileNameExtensionFilter) fileFilter;
String extension = fileNameExtensionFilter.getExtensions()[0];
String newName = file.getName() + "." + extension;
file = new File(file.getParent(), newName);
}
System.out.println("The selected file is: " + file.getAbsolutePath());
}
}
For that you have to get the filefilter selected by the user after he presses the validating button of the JFileChooser and compare the filefilter description with the list of your extensions before initializing the file object with the specified extension in your code if there is a match. I don't know if you will understand me.
Modelexcel model = new Modelexcel();
JFileChooser selectFile = new JFileChooser();;
File file;
JButton btnExporterVersExcel = new JButton("Exporter vers Excel");
btnExporterVersExcel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(selectFile.showDialog(null, "Exporter")==JFileChooser.APPROVE_OPTION) {
String extension=selectFile.getFileFilter().getDescription();
if(extension.contains("(*.xlsx)")) {
file= new File(selectFile.getSelectedFile()+".xlsx");
}else if(extension.contains("(*.xls)")){
file= new File(selectFile.getSelectedFile()+".xls");
}
if(file.getName().endsWith("xls") ||
file.getName().endsWith("xlsx")) {
JOptionPane.showMessageDialog(null, model.Export(file, table));
}else {
JOptionPane.showMessageDialog(null, "Format invalid");
}
}
}
});
This is a fragment of my code to save files in ".xls" and ".xlsx" formats. Hope a look through it will help you
I am trying to move files from one directory to another delete that file from source directory after moving.
for (File file : files) {
if (file != null) {
boolean status = moveFile(file, filePath, name, docGroupId);
if (status) {
//some operations....
}
}
}
public static boolean moveFile(final File file, final String filePath, final String groupName, Integer docGroupId) {
// TODO Auto-generated method stub
String selectedDirectory = filePath + File.separator + groupName;
InputStream in = null;
OutputStream out = null;
try {
if (!file.isDirectory()) {
File dir = new File(selectedDirectory);
if (!dir.exists()) {
dir.mkdirs();
}
String newFilString = dir.getAbsolutePath() +
File.separator + file.getName();
File newFile = new File(newFilString);
in = new FileInputStream(file);
out = new FileOutputStream(newFile);
byte[] moveBuff = new byte[1024];
int butesRead;
while ((butesRead = in.read(moveBuff)) > 0) {
out.write(moveBuff, 0, butesRead);
}
}
in.close();
out.close();
if(file.delete())
return true;
} catch (Exception e) {
return false;
}
}
The program works on Linux-Ubuntu and all files are moved to another directory and deleted from source directory, but in Windows system all files are moved but failed to delete one or two files from source directory. Please note that while debugging the program is working fine.
Consider using Files.delete instead of File.delete. The javadoc says:
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
This should provide the information necessary to diagnose the problem.
So, if problem comes with delete, possible explanations:
you do file.delete() on every files and directories. How do you know the directory is empty ? If not, it will fail, then what happen to next instructions ?
file deletion is OS-dependant. On Windows, you can have many security issues, depending on which user, which rights, which location. You should check with a file-delete-alone program;
last: files can be locked by other programs (even explorer), it is also OS-dependant.
You don't need any of this if the source and target are in the same file system. Just use File.renameTo().
I'm trying to move files using this java code and it can locate the file but not move it, just deletes the directory I'm moving it to.
public void ch() throws Exception{
if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
java.io.File file = FC.getSelectedFile();
Scanner input = new Scanner(file);
System.out.println(file);
Path source = Paths.get(file + "");
Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2");
try {
Files.move(source, target, REPLACE_EXISTING);
} catch (IOException e){
System.out.println("Failed to move the file");
}
}else{
System.out.println("?");
}
}
Add the file name at the end of your destination path, like below:
You could move files with File.ranameTo() method, like this:
file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
In your example:
public void ch() throws Exception{
if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
java.io.File file = FC.getSelectedFile();
try {
file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
} catch (Exception e){
System.out.println("Failed to move the file");
}
}else{
System.out.println("?");
}
}
If you want to use Files.move(), your target path should probably be the full path of the target file, not the destination directory where you want to place it.
Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2\\" + source.getName());
You should use Files.copy() instead of Files.move().
I strongly recommend the use of a third party tool such as Apache Commons IO's FileUtil class for this type of operation.
For example: FileUtil.moveFileToDirectory
Using these types of utilities saves you from many problems you aren't even aware are lurking. Yes, there are limitations to these common utils, but the benefits usually outweigh them in simple cases.
Google Guava is also an option, but I've got less experience there.
Your code is close but there a couple of potential issues. Before I start, I should say that I'm using a Mac (hence the path change), so while this is working for me, there may be some underlying permission issue on your system I can't account for.
1) You aren't using the name of the file you want to move to. You're using the directory you want to move the file to. That's a fair assumption, but you need to make it the fully qualified path and file name.
2) You are creating a Scanner to the to file but not using it. This probably doesn't really matter, but it's best to eliminate unnecessary code.
3) You don't validate the path that was created by getting the Path instance returned from Files.move().
Here is my example code. I tested it and it worked fine. Again, I'm using a Mac, so take that into account.
public void moveFile(){
JFileChooser fc = new JFileChooser("/");
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
System.out.println("Chosen File: " + file.getAbsolutePath());
String newFileName = System.getProperty("user.home")+File.separator+file.getName();
System.out.println("Attempting to move chosen file to destination: " + newFileName);
Path target = Paths.get(newFileName);
try {
Path newPath = Files.move(file.toPath(), target, REPLACE_EXISTING);
System.out.println("Path returned from move: " + newPath);
} catch (IOException e){
// Checked exceptions are evil.
throw new IllegalStateException("Unable to move the file: " + file.getAbsolutePath(),e);
}
}
}
The output from one of the tests:
Chosen File: /Users/dombroco/temp/simpleDbToFileTest1.txt
Attempting to move chosen file to destination: /Users/dombroco/simpleDbToFileTest1.txt
Path returned from move: /Users/dombroco/simpleDbToFileTest1.txt
I want to validate if all the files in a directory are of a certain type. What I did so far is.
private static final String[] IMAGE_EXTS = { "jpg", "jpeg" };
private void validateFolderPath(String folderPath, final String[] ext) {
File dir = new File(folderPath);
int totalFiles = dir.listFiles().length;
// Filter the files with JPEG or JPG extensions.
File[] matchingFiles = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(ext[0])
|| pathname.getName().endsWith(ext[1]);
}
});
// Check if all the files have JPEG or JPG extensions
// Terminate if validation fails.
if (matchingFiles.length != totalFiles) {
System.out.println("All the tiles should be of type " + ext[0]
+ " or " + ext[1]);
System.exit(0);
} else {
return;
}
}
This works fine if the file name have an extension like {file.jpeg, file.jpg}
This fails if the files have no extensions {file1 file2}.
When I do the following in my terminal I get:
$ file folder/file1
folder/file1: JPEG image data, JFIF standard 1.01
Update 1:
I tried to get the magic numbers of the file to check if it is JPEG:
for (int i = 0; i < totalFiles; i++) {
DataInputStream input = new DataInputStream(
new BufferedInputStream(new FileInputStream(
dir.listFiles()[i])));
if (input.readInt() == 0xffd8ffe0) {
isJPEGFlag = true;
} else {
isJPEGFlag = false;
try {
input.close();
} catch (IOException ignore) {
}
System.out.println("File not JPEG");
System.exit(0);
}
}
I ran into another problem. There are some .DS_Store files in my folder.
Any idea how to ignore them ?
Firstly, file extensions are not mandatory, a file without extension could very well be a valid JPEG file.
Check the RFC for JPEG format, the file formats generally start with some fixed sequence of bytes to identify the format of the file. This is definitely not straight forward, but I am not sure if there is a better way.
In a nutshell you have to open each file, read first n bytes depending on file format, check if they match to file format you expect. If they do, its a valid JPEG file even if it has an exe extension or even if it does not have any extension.
For JPEGs you can do the magic number check in header of the file:
static bool HasJpegHeader(string filename)
{
using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
{
UInt16 soi = br.ReadUInt16();
UInt16 jfif = br.ReadUInt16();
return soi == 0xd8ff && jfif == 0xe0ff;
}
}
More complete method here which covers EXIFF as well: C# How can I test a file is a jpeg?
One good (though expensive) check for validity as an image understood by J2SE is to try to ImageIO.read(File) it. That methods throws some quite helpful exceptions if it does not find an image in the file provided.
I tried to specify attachments.path property in my application.conf file, but this had no effects.
In the documentation of play 2.0.1 I didn't find anything explaining how to change uploaded files directory.
Am I missing something?
Although there is no such variable in application.conf you can easily add it and use in your method. Call it as you wish ie:
new line in application.conf:
myUploadPath = "/home/your-account/some/custom/upload/folder/"
according to the documentation sample:
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
MultipartFormData.FilePart picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
// added lines
String myUploadPath = Play.application().configuration().getString("myUploadPath");
file.renameTo(new File(myUploadPath, fileName));
return ok("file saved as " + myUploadPath + fileName);
} else {
flash("error", "Missing file");
return redirect(routes.Application.uploadform());
}
}
Using this approach you can or even should perform filename clash check before renaming, to prevent random overwriting.