How to create an utf8 file from stringbuilder object in Java - java

I have a problem with file encoding. I have a method which exports my DB to a XML in a format I created. The problem is that the file is created with ANSI encoding and I need UTF-8 encoding (some spanish characters aren't shown propperly on ANSI).
The XML file is generated from a StringBuilder object: I write the data from my DB to this StringBuilder object and when I have copied all the data I create the file.
Any help is gratefully received. Thanks in advace.
Edit: This is part of my source:
XMLBuilder class:
...
public XmlBuilder() throws IOException {
this.sb = new StringBuilder();
}
...
public String xmlBuild() throws IOException{
this.sb.append(CLOSE_DB);
return this.sb.toString();
}
...
Service class where I generate the XML file:
XmlBuilder xml = new XmlBuilder();
... (adding to xml)...
xmlString = xml.build();
file = createXml(xmlString);
...
createXml:
public File createXml(String textToFile) {
File folder = new File("xml/exported/");
if (!folder.exists()) {
folder.mkdirs();
}
file = new File("xml/exported/exportedData.xml");
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//if file exists, then delete it and create it
else {
file.delete();
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = textToFile.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
return file;
}

File file = new File("file.xml");
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
writer.write("<file content>");
writer.close();

Related

Write to File doesn't persist between activities

I'm writing and reading from a file and it works perfectly fine. However when the activity is switched or the app is closed it appears that the file is deleted or some such as null is returned when trying to read from the file. I believed it may be because I have an onCreate blank write to the file but that should only run upon the launch to make sure the file is created. I don't mind if the file doesn't persist between launches however it should at least persist between activities.
//in oncreate is writeToHistory("");
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void btnAnsClicked(View v) throws IOException {
File path = getApplicationContext().getFilesDir();
File file = new File(path,"JWCalcHistory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String oldAns = br.readLine();
if (!(oldAns.equals("null") || oldAns.equals(""))) {
if (Character.isDigit(readableSum.charAt(readableSum.length() - 1))) {
oldAns = "*" + oldAns;
}
UpdateSum(oldAns);
}
}
If someone can point out a way to make the contents of the file persist always until it is programmatically deleted or cleared then please let me know. The file doesn't already exist and is created upon the code being run.
You need to check if the file exists first. Something like this:
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
if(file.exists()) return;
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}

How to encrypt an excel in an InputStream and write to an OutputStream?

I'm using this within an application where writing to a file is not possible. The data is always in streams. I get the XLSX file in an inputstream and I would like to set a password and write it to an outputstream.
public void encrptXslxFile(InputStream inStream, OutputStream outStream){
POIFSFileSystem fs = null;
EncryptionInfo info = null;
OutputStream fos;
OPCPackage opc = null;
try {
info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("coffee");
//inStream = new FileInputStream("C:\\ProjectWork\\Community\\excelfile.xlsx");
fs = new POIFSFileSystem();
opc = OPCPackage.open(inStream); //from parameter
OutputStream os = enc.getDataStream(fs);
opc.save(os);
os.close();
//fos = new FileOutputStream("C:\\ProjectWork\\Community\\excelfilepwd.xlsx");
//fs.writeFilesystem(fos);
//fos.close();
fs.writeFilesystem(outStream); // from parameter
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
While reading from the file and writing to the file, it encrypts fine. But if I use the function and then get the outputstream, and later write it, it creates a zero kb file.
Is this even possible?
I tested with the code below to makes sure the inputstream is good.
public void encrptXslxFile(InputStream inStream, OutputStream outStream){
try {
IOUtils.copy(inStream, outStream);
} catch (IOException e) {
e.printStackTrace();
}
}
I was able to write the outputstream to a file.
Since I cannot create files and POI internally uses files, I had to specifically set the temp directory for POI to use.
TempFile.setTempFileCreationStrategy(new TempFileCreationStrategy() {
#Override
public File createTempFile(String prefix, String suffix) throws IOException {
// check dir exists, make if doesn't
if(!fileTempDir.exists()){
fileTempDir.mkdir();
fileTempDir.deleteOnExit();
}
File newFile = File.createTempFile(prefix, suffix, fileTempDir);
return newFile;
}
#Override
public File createTempDirectory(String strPath) throws IOException {
if(!fileTempDir.exists()){
fileTempDir.mkdir();
fileTempDir.deleteOnExit();
return fileTempDir;
}else {
return Files.createTempDirectory(strPath).toFile();
}
}
});
This worked for me.

corrupt pdf file while writing the bytes to stream

Facing a problem while implementing a java-ws service for downloading a pdf file from another webservice. Below is the piece of code for the same.decode() is used because of the webservice(this java code is invoking) is responding with encoded binary-base-64. I could see the PDF is downloaded in the given location but when i open with pdf reader, it says the file is corrupt. Could you please help me ?
public DownloadFileResponse DownloadResponseMapper(Header header, DownloadDocumentResponseType response){
DownloadFileResponse result = new DownloadFileResponse();
result.setHeader(header);
Status status = new Status();
status.setStatusCode(String.valueOf(String.valueOf(response.getStatus().getStatusCode())));
status.setStatusMessage(response.getStatus().getMessage());
result.setStatus(status);
if(String.valueOf(String.valueOf(String.valueOf(response.getStatus().getStatusCode()))) != "0") {
String qNameFile = FileExchange.getProperty("fileSystem.sharedLocation") + "/" + "result.pdf";
try {
byte[] fileContent = FileUtil.decode(response.getFile());
System.out.println(response.getFile());
FileUtil.writeByteArraysToFile(qNameFile, fileContent);
} catch (Exception e) {
_logger.info(e.getStackTrace());
}
// calculate the hash of the file using two algorithm SHA-256/SHA-512
List<FileHashType> hashes = FileUtil.calculateHash(result.getFile());
result.setFileHash(hashes);
}
return result;
}
public static void writeByteArraysToFile(String fileName, byte[] content) throws IOException {
File file = new File(fileName);
BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file));
writer.write(content);
writer.flush();
writer.close();
}

zip creation error in java

I am using ZipOutputStream,FileOutputStream and FileInputStream.
First I created a folder with one file. It successfully created. Then I tried to create zip files. Dynamically, it creates file first time correctly but at second time , third time it gives error while opening it.
Error: zip [path/././file.zip] Cannot open The process cannot access the file because it is being used by another process.
I created following code in java,
My Code:
demopath+="/myzip"+po.getPoid();
createDir(demopath);
createFileForFamilies("My content", demopath+"/file");
this.zipDirectory(new File(demopath), demopath+".zip");
My file creator function:
public String createFileForFamilies(String content, String path) {
FileOutputStream fop = null;
File file;
try {
file = new File(path);
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
return ("Done");
} catch (IOException e) {
System.err.println(e);
return ("Done");
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
System.err.println(e);
return ("Abort");
}
}
}
My Zip creation function:
public void zipDirectory(File dir, String zipDirName) {
try {
populateFilesList(dir);
//now zip files one by one
//create ZipOutputStream to write to the zip file
FileOutputStream fos = new FileOutputStream(zipDirName);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String filePath : filesListInDir) {
System.out.println("Zipping " + filePath);
//for ZipEntry we need to keep only relative file path, so we used substring on absolute path
ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length() + 1, filePath.length()));
zos.putNextEntry(ze);
//read the file and write to ZipOutputStream
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thank you Boris...
This is a solution:
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/"+zipPath+".zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
java.nio.file.Path externalTxtFile;
java.nio.file.Path pathInZipfile ;
externalTxtFile = Paths.get(gamesPath);
pathInZipfile = zipfs.getPath("/file.txt");
Files.copy(externalTxtFile, pathInZipfile,
StandardCopyOption.REPLACE_EXISTING);
}

Android cannot write text into resource file

I created a raw folder inside res (res/raw) and I also created my_text_file.txt file.
Now I want to write something in this file.
I wrote some code but I cannot write (for example) a simple string.
This is my code.
If anyone knows what is wrong in my code, please help me
try {
FileOutputStream fos = openFileOutput("my_text_file.txt",
Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("17");
osw.flush();
osw.close();
} catch (java.io.IOException e) {
// do something if an IOException occurs.
}
You can read your file but not alter the file on the resources folder.
What you can do is to save the file in the external storage then start to alter the file.
Dont forget to set the permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You shouldn't write to resource files. It exist to store data that you put here before compilation. If you want to save some information in file, during runtime you can do something like this:
public static void writeToFile(String fileName, String encoding, String text) {
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), encoding));
writer.write(text);
} catch (IOException ex) {
Log.e(TAG, "", ex);
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
To find path to SD card you can use this method:
Environment.getExternalStorageState()
So you can use this method like this:
writeToFile(Environment.getExternalStorageState() + "/" + "my_text_file.txt", "UTF-8", "my_text");
And don't forgot to set permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
UPD:
You shouldn't use SD card to store some secure information! More information here.
To write data that will be available only for you application, use this code:
public static void writeToInternalFile(String fileName, String text) {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
}
To read from this file:
public static String readFromInternalFile(String fileName) {
FileInputStream fis = openFileInput(, Context.MODE_PRIVATE);
StringBuilder sb = new StringBuilder();
int ch;
while((ch = fis.read()) != -1){
sb .append((char)ch);
}
return sb.toString();
}

Categories

Resources