I've tried this approach:
http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800620/How_To_-_Add_plain_text_or_binary_files_to_an_application.html?nodeid=800687&vernum=0
But it's REALLY slow for slightly large text files. Does anyone know of a better way of reading a plain text file that is included in the project? Is there a way to use FileConnection?
Figured it out using a combination of information:
IOUtilities.streamToBytes(is);
Directly on the input stream. So a more complete example would be as follows:
Class classs = Class.forName("com.packagename.stuff.FileDemo");
InputStream is = classs.getResourceAsStream("/test");
byte[] data = IOUtilities.streamToBytes(is);
String result = new String(data);
Deal? Deal.
Related
Dear brothers Hope you all right?
I'm designing a document program, however, rather to save file .text extension or using any other MS-Office API in java, i want to create my custom file format such as ".sad" extension so that this sort of file can only be read by my programs, how this can be possible?
Your requirement seems ambiguous. Are you looking to make a program that creates MS Office Word documents or plain text files with a custom file extension?
In the case of the former, you can't have a custom extension as MS Word documents, by definition, have a .doc / .docx extension.
However, if you are looking to create a program that produces text files then you can easily have a custom extension. Just look at this tutorial: How to create a file in Java
I already stated why this is a bad idea. Yet I have a solution for you (more like a how-not-to-do-it)
Take your plain text you want to save, convert it to bytes and apply this "highly enthusiastic encryption nobody will ever be able to break" on it:
string plainText = "yadayada";
bytes[] bytesFromText = toBytes(plainText);
bytes[] encrypted = new Array(sizeof(bytesFromText)*2);
for(int i = 0; i < sizeof(bytesFromText); i++){
if((i modulo 2) == 0){
encrypted.push(toByte(Math.random modulo 255));
}
encrypted.push(bytesFromText[i]);
}
I let it up to you to figure out why this is a bad idea and how to decrypt it. ;)
You can create file with any extension
For example,
File f = new File("confidential.sad");
Hope this will work for you :)
Working with custom files in Java
Here is the tutorial that will help you in getting the concept about how to create your own files with custom extension such as .doc or .sad with some information embedded in it and after saving the file you want to read that information form the file.
ZIP
Similar applications often use archives to store data. Consider MS-Word and its documents >with the .docx file extension. If you change the extension of any .docx file to .zip, you >will find that the document is actually a zip archive, with only a different extension.
https://www.ict.social/java/files/working-with-custom-files-in-java-zip-archive
I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation
Github repository
and the answer to your question is so easy
String path = FileSaver
.get()
.save(file,"file.custom");
Reading a word document for example SampleOne.doc and storing it in to a byte[].
#Column(name = "LETTER_WORD_EDITOR_VALUE")
private byte[] letterWordEditorValue;
It is a blob in DB.
I want to read the contents of another word document for Example SampleTwo.doc as byte[] and appending both the byte[] and setting the resultant byte[] in to letterWordEditorValue.
Below is the code to do that.
FileInputStream fileRead = new FileInputStream(fileNameWithPath);
byte[] readData=IOUtils.toByteArray(fileRead);
byte[] one = readData;
byte[] two = inquiryCor.getLetterWordEditorValue();
byte[] combined = new byte[one.length + two.length];
System.arraycopy(one,0,combined,0,one.length);
System.arraycopy(two,0,combined,one.length,two.length);
inquiryCor.setLetterWordEditorValue(combined);
Below is the code to read the letterWordEditorValue and writing in to a Word-File.
fileEditOutPutStream = new FileOutputStream(fileNameWithPath);
fileEditOutPutStream.write(inquiryCor.getLetterWordEditorValue());
fileEditOutPutStream.close();
The contents of word file is not the contents of one+two, Rather it contents readData value only. But when printing the combined.length i.e resultant length is printing sum of one.length+two.length.
Why above code is not appending contents of two word document?
What am i doing wrong? Please guide me to solve this issue.
Thanks!
It's not possible to combine two proprietary documents via simple bytearray-concatenation. That wouldn't even make any sense. You need to parse the two documents via some library and put them together manually. What you were trying to do is like trying to use two motors inside of one car by attaching a second car to the first one ... does not compute!
Apache offers a library for office documents : https://poi.apache.org/
Replace
fileEditOutPutStream.write(inquiryCor.getLetterWordEditorValue());
with
fileEditOutPutStream.write(inquiryCorrespondence.getLetterWordEditorValue());
I have the path to my XML file on my computer, but how can I use selenium (web automation tool) to inject the XML file ?
Usually how it is done (manually) is navigate to the URL and COPY AND PASTE the entire XML text into the provided text box..
Any ideas how to inject the file using automation ? There is no way to "drag" the XML file to the text box and I believe the way I'm thinking that it will work is very complicated.
I think this is actually what you want -
File xml = new File("xmlpath");
String url = xml.getAbsolutePath();
url = url.replace('\\', '/');
url = url.replace(" ", "%20");
String actual = "file:/" + url;
selenium.open(actual);
Then you should be able to get the xml using String theXML = selenium.getText("//rootxmlnode"); Then do what you will with it.
Check out the topic of Data Driven Testing to get you started. Something like this should get you going.
Selenium tool allows you to create an automatically generated code in Java.
So, you need to place any text in the provided text box and generate this Java-test code.
Next step is modifying of the generated test. You have to manually write a simplest code, which will read your XML file, get it contents and paste into the text box. The last thing is replacement (in the generated Java code of test!) of the mentioned above text-block to the contents of read XML.
A simplest way for reading file into a string is using Apache commons-io library.
For example: FileUtils.readFileToString(File file, String encoding) gives you a string object with contents of the file.
I have a project where everything is in UTF-8. I was using the Properties.load(Reader) method to read properties files in this encoding. But now, I need to make the project compatible with Java 1.5, and the mentioned method doesn't exist in Java 1.5. There is only a load method that takes an InputStream as a parameter, which is assumed to be in ISO-8859-1.
Is there any simple way to make my project 1.5-compatible without having to change all the .properties files to ISO-8859-1? I don't really want to have a mix of encodings in my project (encodings are already a time sink one at a time, let alone when you mix them) or change all my project to ISO-8859-1.
With "a simple way" I mean "without creating a custom Properties class from scratch".
Could you use xml-properties instead? As I understand by the spec .properties files should be in ISO-8859-1, if you want other characters, they should be quoted, using the native2ascii tool.
One strategy that might work for this situation is as follows:
Read the bytes of the Reader into a ByteArrayOutputStream.
Once that is completed, call toByteArray() See below.
With the byte[] construct a ByteArrayInputStream
Use the ByteArrayInputStream in Properties.load(InputStream)
As pointed out, the above failed to actually convert the character set from UTF-8 to ISO-8859-1. To fix that, a tweak.
After the BAOS has been filled, instead of calling toByteArray()..
Call toString("ISO-8859-1") to get an ISO-8859-1 encoded String. Then look to..
Call String.getBytes() to get the byte[]
What you can do is open a thread that would read data using a BufferedReader then write out the data to a PipedOutputStream which is then linked by a PipedInputStream that load uses.
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
ReaderRunnable reader = new ReaderRunnable(pos, new File("utfproperty.properties"));
Thread t = new Thread(reader);
t.start();
properties.load(pis);
t.join();
The BufferedReader will read the data one character at a time and if it detects it to be a character data not to be within the US-ASCII (i.e. low 7-bit) range then it writes "\u" + the character code into the PipedOutputStream.
ReaderRunnable would be a class that looks like:
public class ReaderRunnable implements Runnable {
public ReaderRunnable(OutputStream os, File f) {
this.os = os;
this.f = f;
}
private final OutputStream os;
private final File f;
public void run() {
// open file
// read file, escape any non US-ASCII characters
}
}
Now after writing all that I was thinking that someone should've had this problem before and solved it, and the best place to look for these things is in Apache Commons. Fortunately, they have an implementation there.
https://commons.apache.org/io/apidocs/org/apache/commons/io/input/ReaderInputStream.html
The implementation from Apache is not without flaws though. Your input file even if it is UTF-8 must only contain the characters from the ISO-8859-1 character set. The design I had provided above can handle that situation.
Depending on your build engine you can \uXXXX-escape the properties into the build target directory. Maven can filter them via the native2ascii-maven-plugin.
What I personally do in my projects is I keep my properties in UTF-8 files with an extension .uproperties and I convert them to ISO at the build time to .properties files using native2ascii.exe. This allows me to maintain my properties in UTF-8 and the Ant script does everything else for me.
What I just now experienced is, Make all .java files also UTF-8 encoding type (not only properties file where you store UTF-8 characters). This way there no need to use for InputStreamReader also. Also, make sure to compile to UTF-8 encoding.
This has worked for me without any added parameter of UTF-8.
To test this, write a simple stub program in eclipse and change the format of that java file by going to properties of that file and Resource section, to set the UTF-8 encoding format.
I have some data which my program discovers after observing a few things about files.
For instance, i know file name, time file was last changed, whether file is binary or ascii text, file content (assuming it is properties) and some other stuff.
i would like to store this data in XML format.
How would you go about doing it?
Please provide example.
If you want something quick and relatively painless, use XStream, which lets you serialise Java Objects to and from XML. The tutorial contains some quick examples.
Use StAX; it's so much easier than SAX or DOM to write an XML file (DOM is probably the easiest to read an XML file but requires you to have the whole thing in memory), and is built into Java SE 6.
A good demo is found here on p.2:
OutputStream out = new FileOutputStream("data.xml");
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter(out);
writer.writeStartDocument("ISO-8859-1", "1.0");
writer.writeStartElement("greeting");
writer.writeAttribute("id", "g1");
writer.writeCharacters("Hello StAX");
writer.writeEndDocument();
writer.flush();
writer.close();
out.close();
Standard are the W3C libraries.
final Document docToSave = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element fileInfo = docToSave.createElement("fileInfo");
docToSave.appendChild(fileInfo);
final Element fileName = docToSave.createElement("fileName");
fileName.setNodeValue("filename.bin");
fileInfo.appendChild(fileName);
return docToSave;
XML is almost never the easiest thing to do.
You can use to do that SAX or DOM, review this link: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1044810.html
I think is that you want