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));
}
}
}
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.
Reference 1
Reference 2
Related
It couldnt replace the new word and place it in a new file.
I want to create a method that take 4 parameters, one with oldfile , one with new file, one with old word and one with new word and they are all of type string.
I also want to make it so that he case of the first letter the oldWord should be maintained when writing to the in the newFile, e.g. if oldWord was “Hit” and newWord was “Cab” then if “Hit” is found in the oldFile then “Cab” should be written to the newFile.
Im not allowed to use advanced java stuff like hashkeys and all that. Hope that enough infomaton and thank you in advance.
My code couldnt print the new words into the new file instead it just prints 4 more lines of the new words in the old file.
//////
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class part2d {
public static void main(String[] args)
{
modifyFile("test.txt","modify.txt", "Hit", "Cab");
System.out.println("done");
}
static void modifyFile(String oldfile, String newfile, String oldString, String newString)
{
File fileToBeModified = new File("modify.txt");
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String newContent = oldContent.replaceAll(oldString, newString);
writer = new FileWriter(fileToBeModified,true);
writer.write(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Both your reader and your writer are using the fileToBeModified variable. This variable is being set to modify.txt statically for both, so you're not actually reading and writing a new file, instead you're reading then appending the same file content again.
Think about what file you're creating using the BufferedReader/FileReader and the FileWriter, and consider how these are being set.
i have a java code whose functioning is it readers a file using file input stream and after applying some conditions give another file using file output stream
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class Files {
public static void main(String[] args) {
try {
File file = new File("File1.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
File write = new File("File2.txt");
FileWriter fw = new FileWriter(write, true);
BufferedWriter out = new BufferedWriter(fw);
String line;
while ((line = br.readLine()) != null) {
String[] arr = line.split("#");
if (Integer.parseInt(arr[0]) >= 10000) {
out.write(arr[1]);
out.newLine();
}
}
System.out.println("SUCCESS");
br.close();
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
if I want to read millions of data from file and write millions of data in another file how can I edit my code in that case to make my code run fast
I want to make my code fast so that I can fetch or manipulate millions of data
I am trying to read a rectangle.csv file in Java. But while I was reading the file and assigning to a string array, the first element is reading some garbage value along with the first element.
package sample;
import java.io.BufferedReader;
import java.io.FileReader;
import java.time.LocalDateTime;
public class rectangleDemo {
private static Rectangle[] rect ;
private static int count;
static private void loadFile( String filepath)
{
try { // Try catch expression to catch exception
String info=" ";
BufferedReader reader =null;
reader = new BufferedReader(new FileReader(filepath));
while ((info = reader.readLine()) != null)
{
String temp[] = info.split(",");
//
System.out.println(temp[0]);
System.out.println(temp[1]);
}
System.out.println("Database loaded successfully!");
reader.close();
}
catch (Exception e)
{
e.printStackTrace(System.out);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
loadFile("rectangle.txt");
}
Input file
Output
#Tobit, This issue causing while reading the character. So just try setting the correct encoding format while reading the file. Kindly go through this link
Reading text file with UTF-8 encoding
The file 'rectangle.txt' might not be encoded in UTF-8 format. That is why your getting the extra special characters when you read the first line.
You can solve this in two ways,
Change the encoding of rectangle.txt to UTF-8 or
Set the encoding format while reading the file
I just created a UTF-16 file and replicated your issue. The solution would be,
BufferedReader reader =null;
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filepath),"UTF16"));
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 8 years ago.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class test3 {
public static void main(String[] args) {
//write
try {
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt");
PrintWriter pw = new PrintWriter (fw);
pw.println("This is just some test data");
pw.close();
}
catch (IOException e){
System.out.println("Error!");
}
//read
try {
FileReader fr = new FileReader("C:\\Users\\Danny\\Desktop\\Credits.txt");
BufferedReader br = new BufferedReader (fr);
String str;
while ((str = br.readLine()) != null ) {
System.out.println(str + "\n");
}
br.close();
}
catch (IOException e){
System.out.println("File not found!");
}
}
}
This works but over writes the text file each time with the new input. How do I stop this over writing so that all information is stored in the file like an archive.
Pass true to your FileWriter like this -
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true);
The second parameter to the FileWriter constructor will tell it to append to the file.
Docs --> http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,boolean)
Open the file in Append mode the next time you want to write to file.
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true);
Use:
Files.newBufferedWriter(Paths.get("yourfile"), StandardCharsets.UTF_8,
StandardOpenOption.APPEND);
This is my code for reading file and writing file ; i want to write string content to the end of the text file. My aim is to have command on cursor movement/controlling in a text file.
please help me out thanks
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Filing {
public static void main(String[] args) throws IOException
{
String content = "This is the content to write into file";
BufferedReader br =
new BufferedReader(new FileReader("C:/Users/Ashad/Desktop/text.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt");
BufferedWriter bw = new BufferedWriter(fw);
while (line != null)
{
sb.append(line);
sb.append("\n");
line = br.readLine();
}
//** bw.write(content) ; **//
String everything = sb.toString();
System.out.append(everything);
}
finally
{ br.close();}
I couldnot write String content after the text already present on the file.
i want to write string content to the end of the text file
Then just use the overload of the FileWriter constructor that takes an append flag:
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt", true);
Personally though, I'd prefer to use FileOutputStream and an OutputStreamWriter - that way you can specify the encoding.
Create the FileWriter in append mode:
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt", true);