How to write in arabic in arraylist - java

I have an application that reads a file then a user updates the file with different language and saves it. But whenever anyone changes the language and saves the txt file change the letters into symbols ??? I think i have to save it as utf-8 formatted. Any idea?
The next part of code where i get the data from a jtable and save it to a file when user click at save button.
Note: there is nothing wrong with the code. The problem is that the file has to be saved as utf-8.
if(buttonPressed.equals(save)){
File myFile = new File("youFile.srt");
try (PrintWriter writer = new PrintWriter(myFile)) {
for (int i =0 ; i< cModel.getRowCount(); i++)
{
sData.add(cModel.getValueAt(i, 1).toString());
eData.add(cModel.getValueAt(i, 2).toString());
tData.add(cModel.getValueAt(i, 3).toString());
writer.println(i+1 + "\n");
writer.println(sData.get(i)+" --> " + eData.get(i));
writer.println(tData.get(i));
writer.println("\n");
}
}catch(FileNotFoundException ioEx){
ioEx.printStackTrace();
}

PrintWriter need to be clubbed with OutputStreamWriter because it offers constructors to provide the file format. Here is what you can do:
FileOutputStream outputStream = new FileOutputStream(myFile);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(
outputStream, StandardCharsets.UTF_8), true)

You are using a FileWriter. It is better to create a FileOutputStream and then use OutputStreamWriter to write the output. OutputStreamWriter allows you to specify the encoding.
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("youFile.srt"), "UTF-8"));
try {
writer.write(aString);
} finally {
writer.close();
}

Related

Create CSV file without saving it into file system

I've created a Java program to create a csv file, write data into it and then send its contents to the server.
Locally, everything works fine. But the problem is that I don't have write access to the server (permission denied problem).
So, I can't do any chmod 777.
I'm looking for a way to create a csv file without saving into the file system. Something like write into a flow or a stream. I don't really know how it works.
Any help please ?
This was what I have done so far:
public void exportAllToCSV(#PathVariable int id,HttpServletResponse response) throws IOException
String csvFile="test.csv";
File file = new File("test.csv");
//some treatments to get datas (headers and values)
FileWriter writer = new FileWriter(csvFile);
CsvBuilder.writeLine(writer, headers);
CsvBuilder.writeLine(writer, values);
writer.flush();
writer.close();
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=" + csvFile);
final BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while ((line = br.readLine()) != null) {
response.getWriter().write(line + "\n");
}
} finally {
br.close();
}
try {
file.delete(); // I delete the file
} catch (Exception e) {
e.printStackTrace();
}
You can try to write directly to response:
Writer writer = response.getWriter();
CsvBuilder.writeLine(writer, headers);
CsvBuilder.writeLine(writer, values);
writer.flush();
writer.close();
response.setContentType("text/csv");
response.setHeader("Content-Disposition","attachment; filename=" + csvFile);
If that can not be used for some reason and temporary files are also not allowed for you, you can try to use this pretty ugly in-memory variant.
List<Integer> output = new LinkedList<>();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new OutputStream() {
#Override
public void write(int b) throws IOException {
output.add(b);
}
}));
// write all the things via CsvBuilder
final BufferedReader reader = new BufferedReader(new InputStreamReader(new InputStream() {
#Override
public int read() throws IOException {
if (output.size() > 0) {
return output.remove(0);
}
return -1;
}
}));
Assuming that CsvBuilder.writeLine(...) does only accept an instance of java.io.Writer, why not using java.io.StringWriter and java.util.Scanner?
// ...
StringWriter writer = new StringWriter();
CsvBuilder.writeLine(writer, headers);
CsvBuilder.writeLine(writer, values);
writer.flush();
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=test.csv");
Scanner scanner = new Scanner(new StringReader(writer.toString()));
while (scanner.hasNext()) {
response.getWriter().write(scanner.next() + "\n");
}
// ...
However, I think Andrei Makarevich's answer using response.getWriter() directly is probably the most forward approach. Although, I'm not sure if the line feeds will be added by CsvBuilder since your adding them explicitly!?
You can try, if temporary files are allowed:
File temp = File.createTempFile("test.csv", ".csv");
These files are getting created in the user storage of the system, so like "C:\Users[Username]\AppData" in Windows, or something like that. I don't know the exact path, but that should not be important now.
Check out all the kinds of OutputStreams, that exist in Java, there is more than the FileOutputStream:
https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html
Check the subclasses.
Incase someone still looking for the answer, below code worked for me perfectly
Import the below dependencies
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
Below code, im writing data to ByteArrayOutputStream, instead of FileWriter
ByteArrayOutputStream out = new ByteArrayOutputStream();
CsvWriter csvWriter = new CsvWriter(new BufferedOutputStream(out), ',', Charset.forName("UTF-8"));
String[] data = new String[] { "fieldValueA", "fieldValueB", "fieldValueC" };
csvWriter.writeRecord(data);
csvWriter.close();
You can use StringBuilderWriter to have a writer instead of FileWriter
final Writer writer = new StringBuilderWriter();

New Line while writing into file

I followed this link and I came up with below code
try {
File file = new File(
"C:/dataset.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
List<Integer> data = generateData(args);
// one per line
for (final int i : data) {
bw.write(i);
bw.newLine(); // Here it throws NullPointerException
}
bw.close();
} catch (IOException e) {
System.out.print(e);
}
NOTE: Even if I move bw.newLine(); before for loop, it throws NullPointerException.
Image
Am I missing anything ?
To add a line seperator you could use this.
//to add a new line after each value added to File
String newLine = System.getProperty("line.separator");
and then call it like so:
bw.write(newLine);
EDIT:
since you cant use a System.getProperty with a BufferWriter I would suggest the code below:
private FileOutputStream fOut;
private OutputStreamWriter writer;
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(fOut);
writer.append(.... whatever you wish to append ...);
writer.append(separator);
writer.flush();
fOut.close();
Hope that helps!

Editing file in External Storage

In my app, I am writing a file and storing it in external storage
But everytime I want to edit it, I have to get the data of file, delete it and then recreate it using the new data.
But is there any way to directly edit a existing file instead of deleteing and recreating it?
Thanks to blackbelt for helping me out.
Here is how to do this -
File gpxfile = new File(File address, "filename.txt");
BufferedWriter bW;
try {
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write("file text");
bW.newLine();
bW.flush();
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
This will rewrite the file. If you just want to add a line instead of replacing the whole thing, then replace
bW = new BufferedWriter(new FileWriter(gpxfile));
with
bW = new BufferedWriter(new FileWriter(gpxfile, true));

Java save temporary data to file

I have this code:
for (Record record : Adatok) {
//System.out.println(record.toString2());
act_data=tmp.testtestclass(record);
System.out.println("*******");
System.out.println("Feldolgozás eredménye:");
System.out.println(data_restructure(act_data));
// String content = record.nev + ";" + record.address + "\n"+"asd";
File file = new File("resultset.csv");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data_restructure(act_data) + "\n");
bw.close();
}
My problem is that this loop running time is hours and can be interupting. So I do this filewrite/bufferedwrite in it.
So everytime he get data back than I want to write it to file.
But when I do this it is always write only 1 line to my file than nothing.
How can I improve it? I tried with firewriter, bufferedwriter but It kinda bugging.
I know its a dumb question but I cant figurit out how to solve it cause the basic examples does not works.
You can try to use FileWriter with TRUE parameter:
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true); //see here!
BufferedWriter bw = new BufferedWriter(fw);
By doing this, new Text will be appended to the file.
Put these lines outside (before) the loop. You are overwriting the file in each loop iteration.
File file = new File("resultset.csv");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
Also,
bw.close(); // outside (after) the loop

android bufferedwriter error

I'm working on an android app where I need to create a file and write/read on it using bufferedwrite and bufferedread. The file is declared in the activity as follows:
String string = "string";
File file = new File(this.getFilesDir(), string);
When I try to write to the file using this code, however:
BufferedWriter out = new BufferedWriter(new FileWriter(new File(file)));
out.write("I am a line of text written in" + file);
out.close();
I keep getting a "constructer File(File) is undefined" error. I believe the error has to do with the file declaration, but I'm not sure why.
Any help is greatly appreciated.
String string = "string";
File file = new File(this.getFilesDir(), string);
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("I am a line of text written in" + file);
out.close();

Categories