I want to read excel files in java. I have some excel files with old format (excel 95) and others in new format (excel 2007). I am currently using poi but it is not able to read the excel files with older format. So what I need is a function that passes the filename which will return a boolean with value true if the format is old format (BIFF5) and false if the format is new (BIFF8). The need of this function is to allow me to use jxl in for older format and poi for newer format.
Here is the code I have:
try
{
// create a new org.apache.poi.poifs.filesystem.Filesystem
POIFSFileSystem poifs = new POIFSFileSystem(fin);
w = new HSSFWorkbook(poifs);
}
catch (IOException e)
{
w = null;
throw e;
}
catch (OutOfMemoryError e) // java.lang.OutOfMemoryError:
{
w = null;
throw e;
}
catch (OldExcelFormatException e) // OldExcelFormatException
{
w = null;
System.out.println("OldExcelFormatException");
translateBIFF5();
}
private void translateBIFF5() throws IOException, CmpException
{
ArrayList<String> row = null;
try
{
jxl_w = Workbook.getWorkbook(excelFile);
}
catch (BiffException e)
{
jxl_w = null;
e.printStackTrace();
}
catch (IOException e)
{
jxl_w = null;
throw e;
}
catch (OutOfMemoryError e) // java.lang.OutOfMemoryError:
{
jxl_w = null;
throw e;
}
if (jxl_w != null)
{
try
{
for (currentSheet = 0; currentSheet < jxl_w.getNumberOfSheets(); currentSheet++)
{
jxl_sheet = jxl_w.getSheet(currentSheet);
. . . . .
I'd recommend trying Andy Khan's JExcel instead of POI. I don't think POI is particularly well designed or documented. I've had great luck with JExcel. Try it.
One way is to call the Windows ASSOC and FTYPE commands, capture the output and parse it to determine the Office version installed.
C:\Users\me>assoc .xls
.xls=Excel.Sheet.8
C:\Users\me>ftype Excel.sheet.8
Excel.sheet.8="C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.EXE" /e
Here a quick example :
import java.io.*;
public class ShowOfficeInstalled {
public static void main(String argv[]) {
try {
Process p = Runtime.getRuntime().exec
(new String [] { "cmd.exe", "/c", "assoc", ".xls"});
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String extensionType = input.readLine();
input.close();
// extract type
if (extensionType == null) {
System.out.println("no office installed ?");
System.exit(1);
}
String fileType[] = extensionType.split("=");
p = Runtime.getRuntime().exec
(new String [] { "cmd.exe", "/c", "ftype", fileType[1]});
input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String fileAssociation = input.readLine();
// extract path
String officePath = fileAssociation.split("=")[1];
System.out.println(officePath);
}
catch (Exception err) {
err.printStackTrace();
}
}
}
or
You can search in the registry for the key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths
This will probably require some work, as evidenced by this question:
read/write to Windows Registry using Java
Related
I've been reading the book Beginning Android Games and I came across this code and text:
public static void load(FileIO files) {
BufferedReader in = null;
try { in = new BufferedReader(new InputStreamReader(
files.readFile(".mrnom")));
soundEnabled = Boolean.parseBoolean( in .readLine());
for (int i = 0; i < 5; i++) {
highscores[i] = Integer.parseInt( in .readLine());
}
} catch (IOException e) {
// :( It's ok we have defaults
} catch (NumberFormatException e) {
// :/ It's ok, defaults save our day
} finally {
try {
if ( in != null)
in .close();
} catch (IOException e) {}
}
}
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(".mrnom")));
out.write(Boolean.toString(soundEnabled));
for (int i = 0; i < 5; i++) {
out.write(Integer.toString(highscores[i]));
}
} catch (IOException e) {} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {}
}
}
Next up is a method called save(). It takes the current settings and serializes them to
the .mrnom file on the external storage (e.g., /sdcard/.mrnom). The sound setting and each
high-score entry is stored as a separate line in that file, as expected by the load()
method. If something goes wrong, we just ignore the failure and use the default values
defined earlier. In an AAA title, you might want to inform the user about this loading
error
I am very confused as it says it writes to a new line(in the save method) so that in the load method, which uses readLine() works properly. However, they are only using write() with no /n characters. How will this work? Is it simply a typo?
No, it's not a typo.
BufferedReader read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. Then, it uses as delimiter the common System.lineSeparator() to split the text values.
Check the Javadoc by yourself.
public static void main(String args[]) {
decode E = new decode();
String input = "apple";
encode output = E.compute(input);
System.out.println("input decoded :" +E.d_decode(output))
}
Hi, I want the output to be printed in a file instead of printing it to the console. How do I do that? And I want the file to be created at the run time.I mean I am not adding the output to the already created file
Please be patient as I am new to java
You may use java.nio.file.Files which is available from Java 7 to write contents to a file in runtime. The file will be created if you give a correct path also you can set the preferred encoding.
JAVA 7+
Edited after suggestion of #Ivan
You may use PrintWriter, BufferedWriter, FileUtils etc. there are many ways. I am sharing an example with Files
String encodedString = "some higly secret text";
Path filePath = Paths.get("file.txt");
try {
Files.write(filePath, encodedString, Charset.forName("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
System.out.println("unable to write to file, reason"+e.getMessage());
}
To write multiple lines
List<String> linesToWrite = new ArrayList<>();
linesToWrite.add("encodedString 1");
linesToWrite.add("encodedString 2");
linesToWrite.add("encodedString 3");
Path filePath = Paths.get("file.txt");
try {
Files.write(filePath, linesToWrite, Charset.forName("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
System.out.println("unable to write to file, reason"+e.getMessage());
}
There are a million other ways but I think it would be good to start with because of its simplicity.
Before Java 7
PrintWriter writer = null;
String encodedString = "some higly secret
try {
writer = new PrintWriter("file.txt", "UTF-8");
writer.println(encodedString);
// to write multiple: writer.println("new line")
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
writer.close();
}
i want use my java class on the hadoop hdfs, now i must rewrite my functions.
the problem is, if i use the InputStreamReader my app read wrong values.
here my code (so it's work, i want use the uncommented code part):
public static GeoTimeDataCenter[] readCentersArrayFromFile(int iteration) {
Properties pro = new Properties();
try {
pro.load(GeoTimeDataHelper.class.getResourceAsStream("/config.properties"));
} catch (Exception e) {
e.printStackTrace();
}
int k = Integer.parseInt(pro.getProperty("k"));
GeoTimeDataCenter[] Centers = new GeoTimeDataCenter[k];
BufferedReader br;
try {
//Path pt=new Path(pro.getProperty("seed.file")+(iteration-1));
//FileSystem fs = FileSystem.get(new Configuration());
//br=new BufferedReader(new InputStreamReader(fs.open(pt)));
br = new BufferedReader(new FileReader(pro.getProperty("seed.file")+(iteration-1)));
for(int i =0; i<Centers.length; i++){
String[] temp = null;
try{
temp = br.readLine().toString().split("\t");
Centers[i] = new GeoTimeDataCenter(Integer.parseInt(temp[0]),new LatLong(Double.parseDouble(temp[1]),Double.parseDouble(temp[2])),Long.parseLong(temp[3]));
}
catch(Exception e) {
temp = Seeding.randomSingleSeed().split("\t");
Centers[i] = new GeoTimeDataCenter(i,new LatLong(Double.parseDouble(temp[0]),Double.parseDouble(temp[1])),DateToLong(temp[2]));
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return Centers;
}
maybe someone know this problem?
best regards
i have found the problem. i have get a checksum exception. now i delete all .crc files from my input file. in this way i get no checksum exception and the buffered reader work fine (uncommented code part, upstairs).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I've been trying to rename files and folders in a given folder by finding and replacing a substring in their name. Also, the name of file is contained in their contents also. I need to replace it to the new name.
For Example:
Change "XXX" to "KKK" in all the files and folder names and also in file contents:
Original file name: 0001_XXX_YYY_ZZZ.txt
New file name: 0001_KKK_YYY_ZZZ.txt
Following is the code that I'm using.
When I run the following code without calling the function replaceText(), its renaming the file and folder. But, when I try to change the text of file and then rename the file and folder; contents of file is changed but renaming of both file and folder fails.
Please help.
public class FindReplaceAnywhere {
public static void main(String[] args) {
String find = "XXX";
String replace = "KKK";
String baseLoc = "D:\\0001_XXX_YYY_ZZZ";
FindReplaceAnywhere obj = new FindReplaceAnywhere();
File baseLocObj = new File(baseLoc);
LinkedList<File> baseFolderList = new LinkedList<File>();
// Add base folder object to list
baseFolderList.add(baseLocObj);
// Get list of files in the folder
for(File file: baseLocObj.listFiles()) {
baseFolderList.add(file);
}
// Rename the files, folders & contents of files
obj.rename(baseFolderList, find, replace);
}
public void rename(LinkedList<File> fileList, String find, String replace) {
String tempStr = null;
int beginIndex = 0;
int endIndex = 0;
File tempFile;
System.out.println(">>> Batch Rename Process Begins >>>\n");
for(File aFile:fileList) {
// If Object is File, change the text also
if(aFile.isFile()) {
replaceText(aFile,find,replace);
}
}
for(File aFile: fileList) {
System.out.println("Processing>>>");
System.out.println(aFile.getPath());
if(aFile.getName().contains(find)) {
// Get the name of File object
beginIndex = aFile.getPath().length() - aFile.getName().length();
endIndex = aFile.getPath().length();
tempStr = aFile.getPath().substring(beginIndex, endIndex);
tempStr = tempStr.replace(find, replace);
}
else {
System.out.println("Error: Pattern not found\n");
continue;
}
tempFile = new File(aFile.getParentFile(),tempStr);
boolean success = aFile.renameTo(tempFile);
if(success) {
System.out.println("File Renamed To: "+tempFile.getName());
}
else {
System.out.println("Error: Rename Failed\nPossible Cause: File is open in another application");
}
System.out.println("");
}
}
/**
* Replace the text of file if it contains filename
*/
public void replaceText(File file, String find, String replace) {
String fullText = "";
String line = "";
String fileName = "";
String replaceName = "";
BufferedReader in;
BufferedWriter out;
// Read the file contents
try {
in = new BufferedReader(new FileReader(file));
while((line = in.readLine()) != null) {
fullText+=line+"\n";
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
// Replace the text of file
fileName = file.getName().substring(0, file.getName().indexOf("."));
replaceName = fileName.replace(find, replace);
fullText = fullText.replace(fileName, replaceName);
// Write the replaced text to file
try {
out = new BufferedWriter(new FileWriter(file));
out.write(fullText);
out.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
It doesn't look like you're closing your input (in) file after reading it, which will hold that file open - Under *nix a rename should still work, but it will fail under Windows:
Use a finally block to ensure that the resource is closed.. but only after you're assured that it was opened.
While I'm at it, please allow me to suggest another change to the code:
Move "declarations" to the the absolute last point in the code where they can be made.. avoid declaring early. In this case, both in and out are unnecessarily declared early. There are others; I'll leave that for you to work out.
So, for the input file:
// Read the file contents
try {
BufferedReader in = new BufferedReader(new FileReader(file));
// If you got this far, the file is open...
// use try/finally to ensure closure.
try {
while((line = in.readLine()) != null) {
fullText+=line+"\n";
}
}
finally {
in.close();
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
and for the output file:
// Write the replaced text to file
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file));
try {
out.write(fullText);
}
finally {
out.close();
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
I have few text files. Each text file contains some path and/or the reference of some other file.
File1
#file#>D:/FilePath/File2.txt
Mod1>/home/admin1/mod1
Mod2>/home/admin1/mod2
File2
Mod3>/home/admin1/mod3
Mod4>/home/admin1/mod4
All I want is, copy all the paths Mod1, Mod2, Mod3, Mod4 in another text file by supplying only File1.txt as input to my java program.
What I have done till now?
public void readTextFile(String fileName){
try {
br = new BufferedReader(new FileReader(new File(fileName)));
String line = br.readLine();
while(line!=null){
if(line.startsWith("#file#>")){
String string[] = line.split(">");
readTextFile(string[1]);
}
else if(line.contains(">")){
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
line=br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Currently my code reads the contents of File2.txt only, control does not come back to File1.txt.
Please ask if more inputs are required.
First of all you are jumping to another file without closing the current reader and when you come back you lose the cursor. Read one file first and then write all its contents that match to another file. Close the current reader (Don't close the writer) and then open the next file to read and so on.
Seems pretty simple. You need to write your file once your svnLinks Map is populated, assuming your present code works (haven't seen anything too weird in it).
So, once the Map is populated, you could use something along the lines of:
File newFile = new File("myPath/myNewFile.txt");
// TODO check file can be written
// TODO check file exists or create
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(newFile);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
for (String key: svnLinks.keySet()) {
bw.write(key.concat(" my separator ").concat(svnLinks.get(key)).concat("myNewLine"));
}
}
catch (Throwable t) {
// TODO handle more gracefully
t.printStackTrace();
if (bw != null) {
try {
bw.close();
}
catch (Throwable t) {
t.printStackTrace();
}
}
Here is an non-recursive implementation of your method :
public static void readTextFile(String fileName) throws IOException {
LinkedList<String> list = new LinkedList<String>();
list.add(fileName);
while (!list.isEmpty()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(list.pop())));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("#file#>")) {
String string[] = line.split(">");
list.add(string[1]);
} else if (line.contains(">")) {
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
}
}
Just used a LinkedList to maintain the order. I suggest you to add some counter if you to limit the reading of files to a certain number(depth). eg:
while (!list.isEmpty() && readCount < 10 )
This will eliminate the chance of running the code to infinity(in case of circular reference).