this question has probably been asked and answered 100 times but unfortunately I have not found anything suitable for my issue.
The following situation: I have the problem that when I read properties to change them and then write them again, all special characters are unicode escaped.
for example ":" becomes "\:" or
DescripciĆ³n becomes Descripci\u00F3n
Is there a way to change the store method so that the special characters are not escaped?
Thanks a lot
That's my code to write the properties:
private static void writeUpdatedPropertiesFile(Properties newProperties, File sourceAndDestinationFile) {
sourceAndDestinationFile.delete();
try (FileOutputStream out = new FileOutputStream(sourceAndDestinationFile)) {
newProperties.store(out, null);
}
catch (final IOException e) {
e.printStackTrace();
}
}
You can use store(Writer) instead of store(OutputStream). You can construct an OutputStreamWriter with any charset you wish:
try (Writer out = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(sourceAndDestinationFile),
StandardCharsets.UTF_8))) {
newProperties.store(out, null);
} catch (IOException e) {
e.printStackTrace();
}
Of course, it is your responsibility to know that the file is a UTF-8 file, and to read it using load(Reader) instead of using an InputStream:
try (Reader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(sourceAndDestinationFile),
StandardCharsets.UTF_8))) {
properties.load(in);
} catch (IOException e) {
// ...
}
I solved it with a custom writer method:
private static void writeProperties(Properties properties, File destinationFile) {
try (final BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(destinationFile), "Cp1252"))) {
for (final Object o : properties.entrySet()) {
final String keyValue = o.toString();
writer.write(keyValue + "\r\n");
}
}
catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
I know I'm not doing something correctly. I know the file needs to be Serializable to read a text file.
I've got implements Serializable on the main class. But my readText and my writeText aren't converting.
Nothing is coming in when I read and when I write out the file is not text.
public static ArrayList<String> readText() {
ArrayList<String> read = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Reading serialized file",
FileDialog.LOAD);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File inFile = new File(dirPath + foName);
BufferedReader in = null;
ObjectInputStream OIS = null;
try {
in = new BufferedReader(new FileReader(inFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e1) {
e1.printStackTrace();
while (line != null) {
try {
FileInputStream IS = new FileInputStream(inFile);
OIS = new ObjectInputStream(IS);
inFile = (File) OIS.readObject();
} catch (IOException io) {
io.printStackTrace();
System.out.println("An IO Exception occurred");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace(); // great for debugging!
System.out.println("An IO Exception occurred");
} finally
{
try {
OIS.close();
} catch (Exception e) {
}
}
}
}
return read;
}
public static void writeText(ArrayList<String> file) {
ArrayList<String> write = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Saving customer file",
FileDialog.SAVE);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File outFile = new File(dirPath + foName);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
for (int i = 0; i < write.size(); i++) {
String w = write.get(i);
out.println(file.toString());
}
}
catch (IOException io) {
System.out.println("An IO Exception occurred");
io.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
Nothing is coming in
You're never calling read.add(line) and you're attempting to read the file within an infinite loop inside of the catch block, which is only entered if you are not able to read the file.
Just use one try block, meaning try to open and read the file at once, otherwise, there's no reason to continue trying to read the file if it's not able to be opened
List<String> read = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(inFile)) {
String line = null;
while ((line = in.readLine()) != null) {
read.add(line); // need this
}
} catch (Exception e) {
e.printStackTrace();
}
return read;
Now, whatever you're doing with this serialized object stuff, that's completely separate, and it isn't the file or your main class that needs set to Serializable, it's whatever object you would have used a writeObject method on. However, you're reading and writing String objects, which are already Serializable.
when I write out the file is not text
Not sure what you mean by not text, but if you followed the above code, you'll get exactly what was in the initial file... Anyway, you do not need a write list variable.
You must use the individual lines of ArrayList<String> file parameter instead, but not file.toString()
for (String line:file) {
out.println(line);
}
out.close(); // always close your files and writers
In the method getFileName() created the object BufferedReader and assigned reference to the object to the variable - reader. Then stream closed in the finally.
Then invoked the method readStringsFromConsole(). There creates the same object. But thrown IOException. Why did it happen ?
ps: sorry for my English :)
stacktrace:
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
at java.io.BufferedInputStream.read(BufferedInputStream.java:336)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.test.home04.Solution.readStringsFromConsole(Solution.java:55)
code:
import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
String fileName = getFileName();
ArrayList<String> listStrings = readStringsFromConsole();
writeToFileFromList(fileName, listStrings);
}
public static void writeToFileFromList (String fileName, ArrayList<String> listInputString)
{
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
for (String stringItem : listInputString)
writer.write(stringItem);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static ArrayList<String> readStringsFromConsole() {
BufferedReader reader = null;
ArrayList<String> listInputString = new ArrayList<String>();
String line = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
line = reader.readLine();
if ("exit".equals(line))
break;
listInputString.add(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return listInputString;
}
}
public static String getFileName()
{
BufferedReader reader = null;
String fileName = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
while (fileName == null) {
fileName = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
}
}
If you create a reader from System.in and close it, it also closes System.in, which can't be opened again even if you create another reader.
In short - don't close readers which are created from System.in.
Also as Andreas pointed out in the comment, the general guideline should be that System.in should only ever be wrapped once in the lifetime of the command-line program (whether by Scanner, BufferedReader, or something else), and it should never be closed. The wrapping should likely occur at the beginning of main(), and the wrapper object should either be passed around or stored in a field (static or instance).
Why did it happen ?
It happened because you closed System.in in your getFilename method.
Why not open the stream after the close?
Basically, because you can't, or if you are asking about the behavior of the JVM ... >>it<< can't.
When close() is called, the close gets sent to the operating system which closes and releases the underlying file descriptor. Once closed, the OS does not have enough information to reopen the previous file. And if the file descriptor was for an (unnamed) pipe or socket stream, then the connection cannot be remade because:
the application or service at the other end will typically have gone away,
in the case of a TCP/IP socket, the protocol does not allow reconnection.
In short: don't close a stream if you need to read or write more from / to it later, and avoid closing System.{in,out,err} entirely.
Now if your application had a filename or a host / port, it could open a new FileReader or connect a new socket. But in the case of the System.* streams, that information is not available to the application (or the JVM).
But in your particular case, I suspect that your intention is that getFileName returns the filenames supplied one at a time; i.e. each call returns the next filename. If that is the case, you will have to implement it differently:
It shouldn't close the stream or the reader.
It shouldn't open the reader (probably).
It should return the first (or next) line that it reads rather than reading all lines and returning the last one, as it currently does.
You are closing the stream from System.in. Closed stream needs to be opened before reusing it. Don't close them if you create them from System.in.
Try this,
import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
String fileName = getFileName();
ArrayList<String> listStrings = readStringsFromConsole();
writeToFileFromList(fileName, listStrings);
}
public static void writeToFileFromList (String fileName, ArrayList<String> listInputString)
{
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
for (String stringItem : listInputString)
writer.write(stringItem);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static ArrayList<String> readStringsFromConsole() {
BufferedReader reader = null;
ArrayList<String> listInputString = new ArrayList<String>();
String line = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
line = reader.readLine();
if ("exit".equals(line)) {
break;
}
listInputString.add(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
//do not close the stream
//reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return listInputString;
}
}
public static String getFileName()
{
BufferedReader reader = null;
String fileName = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
while (fileName == null) {
System.out.println("Enter a file name: ");
fileName = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
//do not close the stream
//reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
}
}
I have the following code to write in three files. I have printed the Strings before writing to ensure they have some data in them, the printed Strings show the data given to them by calling this function but on creation of file the files are empty.
Please suggest something.
public static void save(String editedFileText,String srcFileText,String translFileText)throws IOException {
JFileChooser chooser = new JFileChooser();
System.out.println(editedFileText);
System.out.println(srcFileText);
System.out.println(translFileText);
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Get in the habit of creating all Writers, Readers, InputStreams and OutputStreams in try-with-resources statements. It ensures they will be properly closed:
try (FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt")) {
edit.write(editedFileText);
}
try (FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt")) {
srcFile.write(srcFileText);
}
try (FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt")) {
trans.write(translFileText);
}
If you're just writing a single String, you have the option of using Files.write, which allows you to forego the use of a Writer altogether:
Files.write(Paths.get(chooser.getSelectedFile()+".txt"),
editedFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_srcText"+".txt"),
srcFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_translFile"+".txt"),
translFileText.getBytes());
Add a finally to close the opened files, but first you need to declare them outside the try catch finally:
FileWriter edit,srcFile, trans;
edit = srcFile = trans = null;
try {
edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}finally{
if(edit != null)
edit.close();
if(srcFile != null)
srcFile.close();
if(trans != null)
trans.close();
}
FileWriter writer=null;
try {
writer = new FileWriter(filename);
writer.write(sb.toString());
} catch (Exception e) {
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I got a Follower-check function in my twitch.bot and i need a read/write solution for it.
It should do the following:
Read an given Number(int) out of the file
Write a new Number to the file and delete the old one
Create the file if it doesnt exist
(the File needs only to store 1 number)
So how can i do this?
right now, i got a String Reader and as soon as i read it i parse it into an INT but i only got errors so i think it doesnt work that way so im searching an option for writing/reading the int already without parsing it from a string.
import java.io.*;
public class FollowerChecker {
public static StringBuilder sb;
static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
public static void Writer() {
FileWriter fw = null;
try {
fw = new FileWriter("donottouch.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringWriter sw = new StringWriter();
sw.write(TwitchStatus.totalfollows);
try {
fw.write(sw.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It appears to be way more complicated than it should be. If you just want to write a number without parsing it as text you can do this.
BTW You may as well use a long as it will use the same disk space and store more range.
public static void writeLong(String filename, long number) throws IOException {
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename))) {
dos.writeLong(number);
}
}
public static long readLong(String filename, long valueIfNotFound) {
if (!new File(filename).canRead()) return valueIfNotFound;
try (DataInputStream dis = new DataInputStream(new FieInputStream(filename))) {
return dis.readLong();
} catch (IOException ignored) {
return valueIfNotFound;
}
}
I am newbie in android development. Today for i was trying to display all my practiced programs of java in my application. I want the application to read the data written in .txt file.
In which folder should I store all my programs? They are more than 100.
I want to display the content of program 2 when I clicked the 2 on the list view or any other
Can we store the text files in database? If so how can I access them ? How can I read them?
Any basic ideas how can I solve this?
You can kept text file in raw / assets folder.
To read them just use this code.
From Assets:
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("YourTextFile.txt")));
From Raw:
InputStream inputStream = context.getResources().openRawResource(R.id.yourresoureid);
InputStreamReader inputreader = new InputStreamReader(inputStream)
as you are a java programmer no need to tell how to read data from InputStream, if your really want then tell me I will post the rest of the code.
Saving that huge amount of data in data base is not a good idea.
Example to read data from InputStream
BufferedInputStream bis=new BufferedInputStream(inputstream);
ByteArrayBuffer baf=new ByteArrayBuffer(1000);
while((k=bis.read())!=-1)
{
baf.append((byte)k);
}
String results=new String(baf.toByteArray());
Start with something easy and work up to the database option.
Yes, the answer would be quite long, and I think a tutorial on SQLite would be a place to start on this.
2,1. Try putting your text files in the assets folder and reading them like this. This code reads a file, and dumps it line by line into the log.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
AssetManager assetManager = getAssets();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
assetManager.open("hi.txt")));
// InputStream inputStream = assetManager.open("hi.txt");
// BufferedReader br = new BufferedReader(
// new InputStreamReader(inputStream));
String lineIn;
while ((lineIn = br.readLine()) != null) {
Log.d("ReadTheDamnFile", lineIn);
}
assetManager.close();
} catch (IOException e) {
}
}
try this its work fine :)
try
{
if(poslist==0)
{
in = this.getAssets().open("file1.txt");
iv.setBackgroundResource(R.drawable.fileimage1);
}
}
catch (IOException e)
{
e.printStackTrace();
}
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
String s ="";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
while (line != null)
{
s = s + line;
s =s+"\n";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
tv.setText(""+s);
}
public void onClick(View v){
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line != null){
tv.setText(line);
} else {
//you may want to close the file now since there's nothing more to be done here.
}