Writing a file in j2me - java-me

My code is not working and not giving any exception:
OutputConnection con = (OutputConnection) Connector.open("file:///epsd/rescuer.txt", Connector.WRITE);
System.out.println("below con");
OutputStream out = con.openOutputStream();
PrintStream ps = new PrintStream(out);
System.out.println("below ps");
ps.println(name+"!"+no+"!"+"!"+mtype+"!#!");
System.out.println("below println");
ps.close();
con.close();
Control doesn't reach after OutputConnection line. Is this how to append data to a text file in J2ME?

Use the following to get the SDCard path and concat it with your file name
String memoryCardPath = System.getProperty("fileconn.dir.memorycard");
String filePath = memoryCardPath + "/rescuer.txt";
OutputConnection con = (OutputConnection) Connector.open(filePath, Connector.WRITE);

Related

Python :Special characters only seen when reading a file generated from unity

I am reading a file from python, this file is generated from unity, the problem is when I read the text from python am getting special characters that does not exist in the file
This is what the file look like when I open it in the desktop:
il tien en son bec un fromage
This is what the file looks lile when open it from python 3.6
ï»؟il tien en son bec un fromage
This is the code from python:
path = ('C:\\Users\\HP\\Documents\\test.txt')
with open(path,'r', encoding="utf-8") as f:
for line in f :
print(line)
test = nltk.word_tokenize(line)
print(test)
And this is the code from unity:
public void Save (){
string Ph = Phrase.text;
if (File.Exists ("C://Users//HP//Documents//test.txt")) {
File.Delete ("C://Users//HP//Documents//test.txt");
StreamWriter file = new StreamWriter ("C://Users//HP//Documents//test.txt", true, Encoding.UTF8);
UTF8Encoding utf8 = new UTF8Encoding ();
byte[] encodedBytes = utf8.GetBytes (Ph);
file.WriteLine (Ph);
}
This is so confusing
UPDATE:
NOW adding encoding="utf-8-sig" solved the problem in case this would help anyone
Setting the encoding to encoding="utf-8-sig" saved the problem

How to play a single audio file from a collection of 100k audio files split into two folders?

I have placed two media folders into a single zip folder, and the total is 100k media files in the zip folder. I need to play a single file from particular folder of the zip folder. The problem is, first the total content of the Zip folder is completely read and then the necessary file is accessed. So, it takes more than 55 seconds to play a single file. I need a solution to reduce the time consumed to play the audio files.
Below is my code :
long lStartTime = System.currentTimeMillis();
System.out.println("Time started");
String filePath = File.separator+"sdcard"+File.separator+"Android"+File.separator+"obb"+File.separator+"com.mobifusion.android.ldoce5"+File.separator+"main.9.com.mobifusion.android.ldoce5.zip";
FileInputStream fis = new FileInputStream(filePath);
ZipInputStream zis = new ZipInputStream(fis);
String zipFileName = "media"+File.separator+"aus"+File.separator+fileName;
String usMediaPath = "media"+File.separator+"auk"+File.separator;
ZipEntry entry;
int UnzipCounter = 0;
while((entry = zis.getNextEntry())!=null){
UnzipCounter++;
System.out.println(UnzipCounter);
if(entry.getName().endsWith(zipFileName)){
File Mytemp = File.createTempFile("TCL", "mp3", getActivity().getCacheDir());
Mytemp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(Mytemp);
for (int c = zis.read(); c!=-1; c= zis.read()){
fos.write(c);
}
if(fos!=null){
mediaPlayer = new MediaPlayer();
}
fos.close();
FileInputStream MyFile = new FileInputStream(Mytemp);
mediaPlayer.setDataSource(MyFile.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(this);
long lEndTime = System.currentTimeMillis();
long difference = lEndTime - lStartTime;
System.out.println("Elapsed milliseconds: " + difference);
mediaPlayer.setOnErrorListener(this);
}
zis.closeEntry();
}
zis.close();
Try to not re-unzip the file because it consume too much time.
Instead of re-unzip the file, you can follow the following step:
Unzip file when first time app is launch. Set flag that we have launch the app before, use preferences.
On the next launch, check the flag. If app never launched before, goto first step. If it had launched before find the file and play.
If you really can't use those step, because it's your requirement, you can try using truezip vfs. But be aware that I've never use it before.
Here the library:
https://truezip.java.net/, https://github.com/jruesga/android_external_libtruezip

Base64 decode to file groovy

Trying to decode base64 and write it to file using groovy
File f = new File("c:\\document1.doc")
PrintWriter writer = null
byte[] b1 = Base64.decodeBase64(info.getdata());
writer = new PrintWriter(f)
writer.print(b1)
writer.close()
This creates a byte[] values like [-121,25,-180....] printed to file.
How to get original data into the file.
You could use a binary stream instead of a Writer:
File f = new File("c:\\document1.doc")
FileOutputStream out = null
byte[] b1 = Base64.decodeBase64(info.getdata());
out = new FileOutputStream(f)
try {
out.write(b1)
} finally {
out.close()
}
But far simpler is to use the Groovy JDK extension File.setBytes:
new File("c:\\document1.doc").bytes = Base64.decodeBase64(info.getdata())
From https://gist.github.com/mujahidk/7fdda0c69d11fc3e4a0907ce4ea77537:
def text = "Going to convert this to Base64 encoding!"
def encoded = text.bytes.encodeBase64().toString()
println encoded
byte[] decoded = encoded.decodeBase64()
println new String(decoded)

Groovy script to read multiple xml files one at a time from 2 folders and apply xmlunit comparison methods

I have series of xml files placed in 2 separate folders as below. My objective is to read each file one at a time from both folders and apply xmlunit comaprison methods.
Folder1 : actual1.xml
actual2.xml
actual3.xml
Folder2 : compare1.xml
compare2.xml
compare3.xml
Part1: Am reading each file at a time from both folders by using below script. I welcome suggestions if there are more simpler methods to do this
log.info "**********Read files from Folder1************"
def xml_file1 = []
new File("D:\\GroovyTest\\Folder1").eachFile{ f ->
f (f.isFile()&& f.name.contains('.xml'))
{
def filename = f.name[0..-1]
xml_file1.add(filename)
log.info filename
}
}
if (xml_file1.size() <1)
{
testRunner.fail("No request files found")
}
log.info "**********Read files from Folder2************"
def xml_file2 = []
new File("D:\\GroovyTest\\Folder2").eachFile{ f ->
if (f.isFile()&& f.name.contains('.xml'))
{
def filename = f.name[0..-1]
xml_file2.add(filename)
log.info filename
}
}
if (xml_file2.size() <1)
{
testRunner.fail("No request files found")
}
Part2: Script to perform comparison for each combination of xml files contained in array xml_file1 and xml_file2.
Am actually stuck at this part as the below script works for single files if each xml file is kept in a string, but i have to pass an array as arguments since i have series of xml files to be compared. I get a run time error - groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.io.FileInputStream(java.util.ArrayList) error at line: 60
InputStream xml_stream1 = new FileInputStream(xml_file1)
String xml1 = getStringFromInputStream(xml_stream1)
InputStream xml_stream2 = new FileInputStream(xml_file2)
String xml2 = getStringFromInputStream(xml_stream2)
def factory = TransformerFactory.newInstance()
def transformer = factory.newTransformer(new StreamSource(new StringReader(xslt)))
StreamResult result_xml1 = new StreamResult(new StringWriter());
transformer.transform(new StreamSource(new StringReader(xml1)), result_xml1)
xml1 = result_xml1.getWriter().toString()
StreamResult result_xml2 = new StreamResult(newStringWriter());
transformer.transform(new StreamSource(new StringReader(xml2)), result_xml2)
xml2 = result_xml2.getWriter().toString()
XMLUnit.setIgnoreComments(true)
DifferenceListener differenceListener = newIgnoreTextAndAttributeValuesDifferenceListener();
DetailedDiff myDiff = new DetailedDiff(new Diff(xml1, xml2));
myDiff.overrideDifferenceListener(differenceListener);
myDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
log.info "similar ? " + myDiff.similar()
log.info "identical ? " + myDiff.identical()
List allDifferences = myDiff.getAllDifferences();
for (Object object : allDifferences) {
Difference difference = (Difference)object;
log.info(difference);
}
Could someone also help me with methods to ignore empty tags during comparison?
Thanks

From string fo DataSet without passing through HTML file

I have a string with length no more than 4000 chars which is a valid xml. Is there a way to pass it to Dataset without creating a temporary xml file?
At the moment I do so:
string validXml = TextBox1.Text;
string path = Directory.GetCurrentDirectory() + #"\tmp.xml";
FileInfo xmlProcess = new FileInfo(path);
using (StreamWriter sw = xmlProcess.CreateText())
{
sw.WriteLine(validXml);
}
DataSet aDataSet = new DataSet();
aDataSet.ReadXml(reader);
Is there a way to skip this creating and filling the tmp.xml?
Try this:
XmlTextReader reader = new XmlTextReader(new StringReader(validXml));
DataSet aDataSet = new DataSet();
aDataSet.ReadXml(reader);

Resources