no source has been specified Weka using eclipse on windows - java

I'm trying to convert a csv file to arff using some Java code I found, but I keep getting the IO error that no source has been specified.
How should I make the file path because a standard "C:\user\user1\Desktop\folder\file.csv" one isn't working for me?
Here is the code I am using:
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;
import java.io.File;
public class CSV2Arff {
public static void main(String[] args) throws Exception {
// load CSV
CSVLoader loader = new CSVLoader();
loader.setSource(new File("file path"));
Instances data = loader.getDataSet();//get instances object
// save ARFF
ArffSaver saver = new ArffSaver();
saver.setInstances(data);//set the dataset we want to convert
//and save as ARFF
saver.setFile(new File("file path"));
saver.writeBatch();
}
}

Your file path should be specified like this
loader.setSource(new File("C:\\Users\\user1\\Desktop\\file1\\file.csv"));
You should use \\ instead of \.

Related

Reading a data from file gives error says the system cannot find the file specified

Hello Guys I have made a xlsx file in the mentioned location as in figure:
and I have a code as below:-
package com.nischal;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FileRead {
public static void main(String[] args) throws IOException {
File src = new File("D:\\Nischal.xlsx");
FileInputStream fis=new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh1= wb.getSheetAt(0);
System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());
}
}
Though there is nothing wrong it always yields the error called: (The system cannot find the file specified)
Image of the Error:
Any suggestions will be helpful
Maybe you need to cast variable name "fis" to string while sending as parameter to XSSFWorkbook;
XSSFWorkbook wb= new XSSFWorkbook(String.valueOf(fis));
The problem was there when I have created a file i.e I have given the file Name is Nischal.xslx but it is not proper format I have to give file name only Nischal and select extension as .xslx. And Now finally it works.
See Now I have changed my renamed my file as
The Working code is same as above.

create .gitignore with java

I'm aware this question might be a duplicate in some sense but first hear me out.
I tried to create a code where i can create gitignore file with contents and for some reason i always end up having a file with txt extension and without name. Can someone explain this behavior and why?
Example Code:
System.out.println(fileDir+"\\"+".gitignore");
FileOutputStream outputStream = new FileOutputStream(fileDir+"\\"+".gitignore",false);
byte[] strToBytes = fileContent.getBytes();
outputStream.write(strToBytes);
outputStream.close();
You can use java.nio for it. See the following example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class StackoverflowMain {
public static void main(String[] args) {
// create the values for a folder and the file name as Strings
String folder = "Y:\\our\\destination\\folder"; // <-- CHANGE THIS ONE TO YOUR FOLDER
String gitignore = ".gitignore";
// create Paths from the Strings, the gitignorePath is the full path for the file
Path folderPath = Paths.get(folder);
Path gitignorPath = folderPath.resolve(gitignore);
// create some content to be written to .gitignore
List<String> lines = new ArrayList<>();
lines.add("# folders to be ignored");
lines.add("**/logs");
lines.add("**/classpath");
try {
// write the file along with its content
Files.write(gitignorPath, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
It creates the file on my Windows 10 machine without any problems. You need Java 7 or higher for it.

Converting a CSV file to ARFF with weka.jar

For my project, I am using weka.jar. I am converting a CSV file to ARFF using following code:
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;
import java.io.File;
public class CsvArffConverter
{
public static void Convert(String sourcepath,String destpath) throws Exception
{
// load CSV
CSVLoader loader = new CSVLoader();
loader.setSource(new File(sourcepath));
Instances data = loader.getDataSet();
// save ARFF
ArffSaver saver = new ArffSaver();
saver.setInstances(data);
saver.setFile(new File(destpath));
saver.setDestination(new File(destpath));
saver.writeBatch();
}
public static void main(String args[]) throws Exception
{
Convert("C:\\ad\\BSEIT.csv", "C:\\ad\\test.arff");
}
}
However, on executing, I am getting following error:
Cannot create a new output file. Standard out is used.
Exception in thread "main" java.io.IOException: Cannot create a new output file (Reason: java.io.IOException: File already exists.). Standard out is used.
at `enter code here`weka.core.converters.AbstractFileSaver.setDestination(AbstractFileSaver.java:421)
at Predictor.CsvArffConverter.Convert(CsvArffConverter.java:29)
at Predictor.CsvArffConverter.main(CsvArffConverter.java:34)
According to weka mail list, this error is a file issue, may be permission. Other emails suggest to use Java I/O approch to save arff file.
This error is coming from the CSVSaver and indicates that it is unable
to create the directory and/or file that you've specified. More than
likely it is something to do with permissions on where it is trying to
write to.
Try following code.
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;
import java.io.File;
public class CsvArffConverter
{
public static void Convert(String sourcepath,String destpath) throws Exception
{
// load CSV
CSVLoader loader = new CSVLoader();
loader.setSource(new File(sourcepath));
Instances dataSet = loader.getDataSet();
// save ARFF
BufferedWriter writer = new BufferedWriter(new FileWriter(destpath));
writer.write(dataSet.toString());
writer.flush();
writer.close();
}
public static void main(String args[]) throws Exception
{
Convert("BSEIT.csv", "test.arff");
}
}
As you can see, I use relative paths. Since absolute path writing may be blocked due to permission issues.

Identifying file type in Java

Please help me to find out the type of the file which is being uploaded.
I wanted to distinguish between excel type and csv.
MIMEType returns same for both of these file. Please help.
I use Apache Tika which identifies the filetype using magic byte patterns and globbing hints (the file extension) to detect the MIME type. It also supports additional parsing of file contents (which I don't really use).
Here is a quick and dirty example on how Tika can be used to detect the file type without performing any additional parsing on the file:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import org.apache.tika.metadata.HttpHeaders;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaMetadataKeys;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.xml.sax.helpers.DefaultHandler;
public class Detector {
public static void main(String[] args) throws Exception {
File file = new File("/pats/to/file.xls");
AutoDetectParser parser = new AutoDetectParser();
parser.setParsers(new HashMap<MediaType, Parser>());
Metadata metadata = new Metadata();
metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());
InputStream stream = new FileInputStream(file);
parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
stream.close();
String mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
System.out.println(mimeType);
}
}
I hope this will help. Taken from an example not from mine:
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class GetMimeType {
public static void main(String args[]) {
File f = new File("test.gif");
System.out.println("Mime Type of " + f.getName() + " is " +
new MimetypesFileTypeMap().getContentType(f));
// expected output :
// "Mime Type of test.gif is image/gif"
}
}
Same may be true for excel and csv types. Not tested.
I figured out a cheaper way of doing this with java.nio.file.Files
public String getContentType(File file) throws IOException {
return Files.probeContentType(file.toPath());
}
- or -
public String getContentType(Path filePath) throws IOException {
return Files.probeContentType(filePath);
}
Hope that helps.
Cheers.
A better way without using javax.activation.*:
URLConnection.guessContentTypeFromName(f.getAbsolutePath()));
If you are already using Spring this works for csv and excel:
import org.springframework.mail.javamail.ConfigurableMimeFileTypeMap;
import javax.activation.FileTypeMap;
import java.io.IOException;
public class ContentTypeResolver {
private FileTypeMap fileTypeMap;
public ContentTypeResolver() {
fileTypeMap = new ConfigurableMimeFileTypeMap();
}
public String getContentType(String fileName) throws IOException {
if (fileName == null) {
return null;
}
return fileTypeMap.getContentType(fileName.toLowerCase());
}
}
or with javax.activation you can update the mime.types file.
The CSV will start with text and the excel type is most likely binary.
However the simplest approach is to try to load the excel document using POI. If this fails try to load the file as a CSV, if that fails its possibly neither type.

Windows Java File lock when referencing existing file in constructor?

Suppose I do the following in java for a process that stays open:
import java.io.File;
import java.util.Date;
public class LogHolder {
public static void main(String[] args) {
File file1 = new File("myLogFile.log");
while (true) {
System.out.println("Running " + new Date());
}
}
}
Have I locked this file in a way that other windows processes can't write to the log file?
This might help you: FileLock.
No, you haven't locked the file. Here's how the Java documentation summarizes the purpose of java.io.File:
An abstract representation of file and directory pathnames
(In other words, new File() doesn't even open the file.)
You can find the rest here: http://java.sun.com/javase/6/docs/api/java/io/File.html

Categories

Resources