I have this method that access a exisitng file, loop thru each line and replace (string to string) a certain line if the condition is met:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
private void UpdateConfig() {
try {
FileInputStream fstream = new FileInputStream("c:\\user\\config.properties");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains("FTPDate=2014/07/01 00:59:00")) {
System.out.println("FILE " + strLine);
strLine.replace("FTPDate=2014/07/01 00:59:00", "FTPDate=2014/09/10 00:00:00");
//strLine.replace("((19|20)\\d\\d/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])", "2014/09/10 00:00:00");
System.out.println("FILE " + strLine);
}
}
in.close();
} catch (Exception e) {
}
}
In the sysout it seems its being replaced:
FILE FTPDateTejas=2014/07/01 00:59:00
FILE FTPDateTejas=2014/09/10 00:00:00
But when I check the file, the date still stays the same. Am I missing something? anyone knows what I missed out? thank you
When you are doing:
strLine = br.readLine() it loads the next line from the BufferedReader into memory. This means that you have your data on disk and in memory and that those two are not linked to each other in any way. When doing modifications on strLine I believe you have in your code:
strLine = strLine.replace("FTPDate=2014/07/01 00:59:00", "FTPDate=2014/09/10 00:00:00");
As replace doesn't modify the contents of the objects on which it is being called but returns a new String objects (Strings are immutable). So what that does it creates a new object but does not modify your on disk data (as I said, it's not linked to it any more!).
You could think "ok then how do I link those two and override the file in place?". Well Java does provide random file access as described in the doc but the only thing you can do with it is modify characters at a certain position, you cannot insert things in the middle. So what you would have to do is read the rest of your file, make your modification and then append that rest of the file, yes you need to shift things in case your new string with which you are substituting would be shorter/longer than what you are replacing.
That's why an easier solution would be to:
open a new file to write to
write line by line to it (the strings after the replace)
delete the old file and rename the new file
Without copying the file the code would look something like this:
private void UpdateConfig() {
File fstream = new File("c:\\user\\config.properties");
File file = new File("c:\\user\\config.properties-new");
try {
file.createNewFile();
} catch (IOException e) {
// handle
}
try (FileReader in = new FileReader(fstream);
FileWriter fw = new FileWriter(file.getAbsoluteFile())) {
try (BufferedReader br = new BufferedReader(in);
BufferedWriter bw = new BufferedWriter(fw)) {
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.contains("FTPDate=2014/07/01 00:59:00")) {
System.out.println("FILE " + strLine);
strLine = strLine.replace("FTPDate=2014/07/01 00:59:00",
"FTPDate=2014/09/10 00:00:00");
//strLine.replace("((19|20)\\d\\d/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])", "2014/09/10 00:00:00");
bw.write(strLine);
System.out.println("FILE " + strLine);
}
}
}
// copy files here
} catch (IOException e) {
// handle
}
}
There might be some logical/syntactic problems as I was writing in in a plain text editor. I modified the code a bit to use Java 7's try-with-resources, which is a cleaner way of closing resources than what you were doing - in your code when an exception would be thrown the stream might not had been closed.
Related
My requirement is to copy the content from one master file and paste it in temp file.
These files are in .dat file format. The code copy paste the contents perfectly but it comes in one single line.
My need is, it should come in new lines instead of one single line.
public static void JavaCopyFile ()
{
try {
FileReader fr = new FileReader("C:\\Automation\\Master_Template.dat");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("C:\\Automation\\Temp.dat");
String s;
while ((s = br.readLine()) != null) { // read a line
fw.write(s); // write to output file
fw.flush();
}
br.close();
fw.close();
System.out.println("file copied");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please use
writer.write(System.getProperty( "line.separator" ));
to add new line character(s) specific for the OS you use. Also there is no need to flush after each line - one time at the very end is sufficient:
.......
newLine = writer.write(System.getProperty( "line.separator"));
while ((s = br.readLine()) != null) { // read a line
fw.write(s); // write to output file
fw.write(newLine);
}
fw.flush();
.......
Check this link for other solutions:
Create a new line in Java's FileWriter
This question already has answers here:
Write a file in UTF-8 using FileWriter (Java)?
(9 answers)
Closed 5 years ago.
Below is my code, it is intended to take two .ckl files, compare the two, add the new items and create a new merged file. The program executes correctly when run in Netbeans however, when executing the .jar the program doesn't appear to be encoding the file in UTF-8. I am rather new to programming and would like to know where or how I might need to be enforcing this encoding to take place?
** I have removed the Swing code and other lines so that only my method is shown, the method that does all of the comparing and merging.
public void mergeFiles(File[] files, File mergedFile) {
ArrayList<String> list = new ArrayList<String>();
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, false);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
// Going in a different direction. We are using a couple booleans to tell us when we want to copy or not. So at the beginning since we start
// with our source file we set copy to true, we want to copy everything and insert vuln names into our list as we go. After that first file
// we set the boolean to false so that we dont start copying anything from the second file until it is a vuln. We set to true when we see vuln
// and set it to false if we already have that in our list.
// We have a tmpCopy to store away the value of copy when we see a vuln, and reset it to that value when we see an </VULN>
Boolean copy = true;
Boolean tmpCopy = true;
for (File f : files) {
textArea1.append("merging files into: " + mergedFilePathway + "\n");
FileInputStream fis;
try {
fis = new FileInputStream(f);
// BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(mergedFile), "UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
// Skip the close checklist and we can write it in at the end
if (aLine.trim().equals("</iSTIG>")) {
continue;
}
if (aLine.trim().equals("</STIGS>")) {
continue;
}
if (aLine.trim().equals("</CHECKLIST>")) {
continue;
}
if (aLine.trim().equals("<VULN>")) {
// Store our current value of copy
tmpCopy = copy;
copy = true;
String aLine2 = in.readLine();
String aLine3 = in.readLine();
String nameLine = in.readLine();
if (list.contains(nameLine.trim())) {
textArea1.append("Skipping: " + nameLine + "\n");
copy = false;
while (!(aLine.trim().equals("</VULN>"))) {
aLine = in.readLine();
}
continue; // this would skip the writing out to file part
} else {
list.add(nameLine.trim());
textArea1.append("::: List is now :::");
textArea1.append(list.toString() + "\n");
}
if (copy) {
out.write(aLine);
out.newLine();
out.write(aLine2);
out.newLine();
out.write(aLine3);
out.newLine();
out.write(nameLine);
out.newLine();
}
} else if (copy) {
out.write(aLine);
out.newLine();
}
// after we have written to file, if the line was a close vuln, switch copy back to original value
if (aLine.trim().equals("</VULN>")) {
copy = tmpCopy;
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
copy = false;
}
// Now lets add the close checklist tag we omitted before
try {
out.write("</iSTIG>");
out.write("</STIGS>");
out.write("</CHECKLIST>");
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Java has extensive, highly informative documentation. Keep it bookmarked. Refer to it first, whenever you have difficulty. You'll find it's frequently helpful.
In this case, the documentation for FileWriter says:
The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
If you want to be sure your file will be written as UTF-8, replace this:
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, false);
with this:
Writer fstream = null;
BufferedWriter out = null;
try {
fstream = new OutputStreamWriter(new FileOutputStream(mergedFile), StandardCharsets.UTF_8);
For those, who use FileWriter in order to append to an existing file, the following will work
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8)) {
//code
}
You can just run it with the command java -Dfile.encoding=UTF-8 -jar yourjar.jar.
Follow this for more info.
I wrote some code to read in a text file and to return an array with each line stored in an element. I can't for the life of me work out why this isn't working...can anyone have a quick look? The output from the System.out.println(line); is null so I'm guessing there's a problem reading the line in, but I can't see why. Btw, the file i'm passing to it definitely has something in it!
public InOutSys(String filename) {
try {
file = new File(filename);
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (Exception e) {
e.printStackTrace();
}
}
public String[] readFile() {
ArrayList<String> dataList = new ArrayList<String>(); // use ArrayList because it can expand automatically
try {
String line;
// Read in lines of the document until you read a null line
do {
line = br.readLine();
System.out.println(line);
dataList.add(line);
} while (line != null && !line.isEmpty());
br.close();
} catch (Exception e) {
e.printStackTrace();
}
// Convert the ArrayList into an Array
String[] dataArr = new String[dataList.size()];
dataArr = dataList.toArray(dataArr);
// Test
for (String s : dataArr)
System.out.println(s);
return dataArr; // Returns an array containing the separate lines of the
// file
}
First, you open a FileWriter once after opening a FileReader using new FileWriter(file), which open a file in create mode. So it will be an empty file after you run your program.
Second, is there an empty line in your file? if so, !line.isEmpty() will terminate your do-while-loop.
You're using a FileWriter to the file you're reading, so the FileWriter clears the content of the file. Don't read and write to the same file concurrently.
Also:
don't assume a file contains a line. You shouldn't use a do/while loop, but rather a while loop;
always close steams, readers and writers in a finally block;
catch(Exception) is a bad practice. Only catch the exceptions you want, and can handle. Else, let them go up the stack.
I'm not sure if you're looking for a way to improve your provided code or just for a solution for "Reading in text file in Java" as the title said, but if you're looking for a solution I'd recommend using apache commons io to do it for you. The readLines method from FileUtils will do exactly what you want.
If you're looking to learn from a good example, FileUtils is open source, so you can take a look at how they chose to implement it by looking at the source.
There are several possible causes for your problem:
The file path is incorrect
You shouldn't try to read/write the same file at the same time
It's not such a good idea to initialize the buffers in the constructor, think of it - some method might close the buffer making it invalid for subsequent calls of that or other methods
The loop condition is incorrect
Better try this approach for reading:
try {
String line = null;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
System.out.println(line);
dataList.add(line);
}
} finally {
if (br != null)
br.close();
}
I was wondering how one would go about importing a text file. I want to import a file and then read it line by line.
thanks!
I've no idea what you mean by "importing" a file, but here's the simplest way to open and read a text file line by line, using just standard Java classes. (This should work for all versions of Java SE back to JDK1.1. Using Scanner is another option for JDK1.5 and later.)
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(fileName)));
try {
String line;
while ((line = br.readLine()) != null) {
// process line
}
} finally {
br.close();
}
This should cover just about everything you need.
http://download.oracle.com/javase/tutorial/essential/io/index.html
And for a specific example: http://www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html
This might also help: Read text file in Java
I didnt get what you meant by 'import'. I assume you want to read contents of a file. Here is an example method that does it
/** Read the contents of the given file. */
void read() throws IOException {
System.out.println("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new File(fFileName), fEncoding);
try {
while (scanner.hasNextLine()){
text.append(scanner.nextLine() + NL);
}
}
finally{
scanner.close();
}
System.out.println("Text read in: " + text);
}
For details you can see here
Apache Commons IO offers a great utility called LineIterator that can be used explicitly for this purpose. The class FileUtils has a method for creating one for a file: FileUtils.lineIterator(File).
Here's an example of its use:
File file = new File("thing.txt");
LineIterator lineIterator = null;
try
{
lineIterator = FileUtils.lineIterator(file);
while(lineIterator.hasNext())
{
String line = lineIterator.next();
// Process line
}
}
catch (IOException e)
{
// Handle exception
}
finally
{
LineIterator.closeQuietly(lineIterator);
}
How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.