Reputation: 98
How to read a file and then write the data into a .txt file in java? Below is my code. I am reading a file with extension .ivt. There are some tables in .ivt and reset is a text that describes what data is all about. I have to read the text stored in the file and then write it on a text file. I was able to get the data and write it on text file as well. But, when I open the text file and look at what is written, I see many lines of random symbols and spaces. Then, few lines are converted from English to French. I am struggling to find why this is happening. Does this problem occurs while reading data? or is there something wrong with the code?
package description;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
public class FileDescription
{
public static void main(String[] args)
{
// create variables
ArrayList<String> fileLines = new ArrayList<>();
String currLine;
// create file
File file = new File("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\Products.ivt");
FileInputStream fis = null;
BufferedReader br = null;
try
{
fis = new FileInputStream(file);
// construct buffered reader
br = new BufferedReader(new InputStreamReader(fis));
}
catch (FileNotFoundException e)
{
}
try
{
while((currLine = br.readLine()) != null)
{
// add line to the arrayList
fileLines.add(currLine);
}
}
catch (IOException e)
{
}
finally
{
// close buffered reader
try
{
br.close();
}
catch (IOException e)
{
}
}
// write ArrayList on file
PrintWriter pw = null;
try
{
pw = new PrintWriter("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt");
}
catch (IOException e)
{
}
for (int i = 0; i < fileLines.size(); i++)
{
pw.println(fileLines.get(i));
}
}
}
Upvotes: 0
Views: 257
Reputation: 4838
The code seems correct. Just remember to close output writer too. Without specify anything else, you are using plaftorm encoding. I think it's an encoding problem. You can try to read and write in UTF-8 encoding.
For the buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("filename.txt"), StandardCharsets.UTF_8));
And for the writer
pstream = new PrintWriter(new OutputStreamWriter(
new FileOutputStream("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt"), StandardCharsets.UTF_8), true);
To edit result, use an editor with UTF-8.
Upvotes: 1