I have a text file sample.txt which have following lines
sample1.txt
test.ppt
example.doc
content.pdf
I have a dynamic variable called field (example phpcookbook.pdf,sample1.txt) it should compare with each line in sample.txt file and if the text file does not contain the field it should append to sample.txt. I have tried the following code but it's not working:
File insert=new File(sample.txt);
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
while ((strLine = br.readLine()) != null) {
if(!strLine.equals(field)) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field);
bw.close();
}
}
I should get the following output
sample1.txt
test.ppt
example.doc
content.pdf
phpcookbook.pdf
How to compare a text file line by line with a dynamic variable?
If I understand the question correctly, this is what you need:
File insert = new File("sample.txt");
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
Boolean hasLine = false;
while ((strLine = br.readLine()) != null) {
if(strLine.equals(field)) {
hasLine = true;
break;
}
}
br.close();
if (!hasLine) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field + "\n"); // assumes field does not already have a newline
bw.flush();
bw.close();
}
Notice the break;. This will discontinue the while loop, since you already have the answer to what you are looking for.
Your original code was doing:
for every line:
Do I equal field?
Yes: goto next line
No: append field to file and goto next line
But what you WANTED to know was whether or not field appeared in the file at all, not in each line.
You should use Commons IO.
See this working example
package training;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class TestFile {
/**
* #param args
* #throws IOException
*/
private static String field = "phpcookbook.pdf";
private static String fileContent;
public static void main(String[] args) throws IOException {
boolean found = false;
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
if (line.equals(field)) {
found = true;
break;
}
}
if (!found) {
fileContent = FileUtils.readFileToString(file);
fileContent += "\n" + field;
}
FileUtils.write(file, fileContent);
}
}
You should do something like this:
File insert = new File("sample.txt");
boolean isStringPresent = false;
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.equals(field)) {
isStringPresent = true;
}
}
if(!isStringPresent) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field);
bw.close();
}
No answer since you ask for Java, but just to illustrate the power of Unix shell tools:
v=phpcookbook.pdf
grep $v in.txt
[[ $? -eq 1 ]] && echo $v >> in.txt
Related
I am writing a method for my java class. it looks like this so far:
String file_name;
String line;
void addLine(file_name, line){
int line_number;
try {
FileWriter writer = new FileWriter(file_name, true);
PrintWriter out = new PrintWriter(writer);
out.println(line_number + line);
}
catch (IOException e){
System.out.println(e);
}
}
How should I define line_number so it would check how many lines were there in file before I printed out next into it?
int totalLines = 0;
BufferedReader br br = new BufferedReader(new FileReader("C:\\filename.txt"));
String CurrentLine = "";
while ((CurrentLine = br.readLine()) != null) {
++totalLines
}
i think you have to actually read the file by using a bufferedreader. and then keep on incrementing the totalLines till it reach the end of the file
You can count them with a function posted here: Number of lines in a file in Java
They tested it with a 150 MB log file and it seems to be fast.
I've a code which replaces 10:A to 12:A in a text file called sample.txt. Also, the code I've now is changing the file format, which shouldn't. Can someone please let me know how to do the same using regular expression in Java which doesn't change the file format? File has original format as below 10:A 14:Saxws But after executing the code it outputs as 10:A 14:Saxws.
import java.io.*;
import java.util.*;
public class FileReplace
{
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("sample.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null)
{
if (line.contains("10:A"))
line = line.replaceAll("10:A", "12:A") + System.lineSeparator();
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args)
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
It looks like your OS or editor is not able to print correctly line separators generated by System.lineSeparator(). In that case consider
reading content of entire file to string (including original line separators), - then replacing part which you are interested in
and writing replaced string back to your file
You can do it using this code:
Path file = Paths.get("sample.txt");
//read all bytes from file (they will include bytes representing used line separtors)
byte[] bytesFromFile = Files.readAllBytes(file);
//convert themm to string
String textFromFile = new String(bytesFromFile, StandardCharsets.UTF_8);//use proper charset
//replace what you need (line separators will stay the same)
textFromFile = textFromFile.replaceAll("10:A", "12:A");
//write back data to file
Files.write(file, textFromFile.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
public static void doubleSpace(String fileName) {
try {
FileReader reader = new FileReader(fileName);
Scanner in = new Scanner(reader);
String outputFileName = fileName.charAt(0) + ".ds";
PrintWriter pOut = new PrintWriter(outputFileName);
// Opening of files for input and output
while (in.hasNextLine()) {
String line = in.nextLine();
pOut.println(line + "\n");
pOut.print("\n");
// System.out.println(line + "\n"); //Test
}
pOut.close(); // Close the files if they have been opened.
} catch (Exception e) {
}
}
So basically my input file contains
a
b
c
and my output file should look like
a
b
c
However, my output file always contains only abc.
Any help would be much appreciated!
Use a BufferedWriter. It has a .newLine() method. This method will use the platform's default line separator.
And use a BufferedReader. It has a .readLine() method.
Example:
// NOTE: you should really be using UTF-8
final Charset charset = Charset.defaultCharset();
final Path src = Paths.get(filename);
final Path dst = Paths.get(filename + ".ds");
String line;
try (
final BufferedReader reader = Files.newBufferedReader(src, charset);
final BufferedWriter writer = Files.newBufferedWriter(dst, charset);
) {
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
writer.newLine();
}
}
You are likely useing the wrong character(s) for new line for your plattform. Use
System.getProperty("line.separator");
to get the right value.
public class AddSingleInstance {
public void addinstances(String txtpath,String arffpath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("C:\\src\\text.txt"));
FileWriter fw = new FileWriter("C:\\src\\" + test.txt,true);
StringBuilder sb = new StringBuilder();
//String toWrite = "";
String line = null;
while ((line = reader.readLine())!= null){
// toWrite += line;
sb.append(line);
sb.append("\n");
}
reader.close();
fw.write(sb.toString());
fw.flush();
fw.close();
}
}
my code is working on append lines from text file(A) to specific lines in another file(B), like
I
AM
......
(above lines are fixed, cannot be overwriting)
student(New string was added from text file)
now(New string...)
How can I overwrite those lines into file(B) instead of appending them on B?
You can use java.io.RandomAccessFile to access file(B) and write to it at the desired location.
I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}