Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So my program needs to overwrite e.g line 5 in a file. Just the 5th line, keep the others.
We don't know what is the content of line 5.
But I have no idea how to do it, can't found anything about how to do this with BufferedWriter and FileWriter.
I can't write there a code, because.. I just don't know how to do it.:/
A sample solution could look like this
package teststuff;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Btest {
public static void main(String args[])
{
try
{
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "", fivthLine = "";
int x=0;
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
if(x == 4)
{
fivthLine = line;
}
x++;
}
reader.close();
String newtext = oldtext.replaceAll(fivthLine, "blah blah blah");
FileWriter writer = new FileWriter("test.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Note that this is a combination of what Emmanuel wrote and this
It will also replace whats written in the 5th line everywhere on the file, so that another line containing the same content of line 5 will also be overwritten with
"blah blah blah"
by first you can start looking for "How to count lines on a file" like this i found
https://www.geeksforgeeks.org/counting-number-lines-words-characters-paragraphs-text-file-using-java/
Then add counter++ each time you pass a line, when (counter == 5)
then do whatever you need to do..
This is a very simple example of replacing a given line in a file:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class LineReplaceTest
{
public static void main(String... args)
throws Exception
{
int lineToReplace = 5;
String replacementText = "This is a different line";
Path input = Paths.get("input.txt");
Path output = Paths.get("output.txt");
// Use try-with-resources to ensure our readers & writers are closed
try (BufferedReader reader = Files.newBufferedReader(input);
BufferedWriter writer = Files.newBufferedWriter(output)) {
String line;
int lineNumber = 0;
// While there is a line to read from input...
while ((line = reader.readLine()) != null) {
lineNumber++;
// Write out either the line from the input file or our replacement line
if (lineNumber == lineToReplace) {
writer.write(replacementText);
} else {
writer.write(line);
}
writer.newLine();
}
}
// Once we're done, overwrite the input file
Files.move(output, input);
}
}
It ignores several important things line error handling and platform-specific newline handling, but it should at least get you started.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My text file is in the following format having different type of strings such as below:
candle
(air-paraffin)
1,000
°c
(1,800
°f)
smoldering
cigarette:
temperature
13%,
wildlife.[14]
johnston,
f.
h.;
keeley,
j.
bibcode:2009sci...324..481b
(http://adsabs.harvard.edu/abs/2009sci...3
I would like to remove everything except simple words such as the ones below.
smoldering
temperature
That is if a word is even followed by a comma (e.g. smoldering,), I would remove it.
I tried to remove the digits for a start with MyString.replaceAll("^\\d", " ") but even that is not working.
If you load the entire file into memory, with line breaks, you can use a regex like this:
text = text.replaceAll("(?m)^.*[^a-zA-Z\r\n].*(?:\R|$)", "")
Output
candle
smoldering
temperature
For demo see regex101.
It would however be better to do the filtering while you load the text file:
Pattern simpleWord = Pattern.compile("\\p{L}+"); // one or more Unicode letters
try (BufferedReader in = Files.newBufferedReader(Paths.get("path/to/file.txt"))) {
for (String line; (line = in.readLine()) != null; ) {
if (simpleWord.matcher(line).matches()) {
// found simple word
}
}
}
If you want the simple words in a list, you can simplify that with Java 8 stream:
List<String> simpleWords;
try (Stream<String> lines = Files.lines(Paths.get("path/to/file.txt"))) {
simpleWords = lines.filter(Pattern.compile("^\\p{L}+$").asPredicate())
.collect(Collectors.toList());
}
This solution will iterate over the input.txt lines and paste them into output.txt if they match certain regex. After that it will remove output.txt and rename it with input.txt original file.
Class:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Pattern;
public class ReplaceWithRegex {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (Pattern.matches("^[a-zA-Z]+$", line)) {
writer.write(line);
writer.newLine();
}
}
}
if (inputFile.delete()) {
// Rename the output file to the input file
if (!outputFile.renameTo(inputFile)) {
throw new IOException("Could not rename output to input");
}
} else {
throw new IOException("Could not delete original input file ");
}
}
}
Input.txt
candle
(air-paraffin)
1,000
°c
(1,800
°f)
smoldering
cigarette:
temperature
13%,
wildlife.[14]
johnston,
f.
h.;
keeley,
j.
bibcode:2009sci...324..481b
(http://adsabs.harvard.edu/abs/2009sci...3
Input.txt after execution:
candle
smoldering
temperature
Assuming lines are delimiters:
myString.replaceAll("^[^a-z&&[^A-Z]]*$", "");
I am using Mac OS on which I wrote the following java code :
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.FileReader;
class random9
{
public static void main(String[] args) throws Exception
{
String line = null;
BufferedReader br = new BufferedReader(new FileReader("/Users/xyz/Desktop/xyz.txt"));
br.readLine();
}
}
When I run this file I don't get an output although the program runs successfully without any errror.
(P.S : This is the first question I have asked on stack overflow so I apologize if my question is not phrased correctly.)
You are reading a line from you file via the BufferedReader but you did not use it, so nothing happen
You need to store and make something with it like print it
String firstLine = br.readLine();
System.out.println("First line is" + firstLine);
//or simply
System.out.println(br.readLine());
To read a file with multiple lines you may read a new line nonstop until it’s null :
String line;
while((line = br.readLine())!=null){
System.out.println(line); // or something else
}
You can use
System.out.println(br.readLine());
or if file contains more then 1 row then you can use
String str=null;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
I am working on a program that evaluates lisp expressions using a stack implemented by either an array or linked list. I need to read the file in from the first line from right to left. Currently I am reading it in from left to right but I do not understand how I can switch it around. Any help you can give me is greatly appreciated! Thank you!
**I know the program is nowhere near complete, I just need to accomplish this before I can continue.
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.*;
import java.io.BufferedReader;
public class A2Q5{
private static Scanner in;
public static void main (String [] args)
{
if(args.length != 2) {
System.out.println("Please execute as: java A2Q5 type infile");
}
BoundedStack<Double> stack;
if(args[0].equals("0"))
stack = new BSArray<Double>(20);
else
stack = new BSLinkedList<Double>();
// The name of the file to open.
String fileName = args[1];
// This will reference one line at a time
//char c = null;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
for (int i = line.length() - 1; i >= 0; i--){
line.charAt(i);
System.out.println(line.charAt(i));
}
}
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file " + fileName);
}
catch(IOException ex) {
System.out.println("Error reading file " + fileName);
}
}
}
Drop the use of FileInputStream and use BufferedReader that you already prepared but never use. Use its method readLine to read info from your file line by line. Once you got an individual line you can iterate through it character by character from the end of the String to its beginning. This is exactly what you want.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have 3 text files that all contain strings from objects.
I have a GUI with a list that is populated with the contents of one text file. Im currently looking to implement something that would take the line number from the first file and pull out the strings from the same line number in other files. Can anyone recommend anything?
You can use:
String[] lines = secondFileText.split("\n");
P.s.- If that doesn't work try replacing \n with \r\n.
You can split a string into lines:
String[] lines = s.split("\r?\n");
Then you can access the line at any index:
System.out.println(lines[0]); // The array starts at 0
Note: On Windows, the norm for ending lines is to use a carriage-return followed by a line-feed (CRLF). On Linux, the norm is just LF. The regular expression "\r?\n" caters for both cases - it matches zero or one ("?") carriage-returns ("\r") followed by a line-feed ("\n").
BufferedReader will deal well with huge files that won't fit in memory, it's pretty fast and deal with both \r and \n
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadByLine {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
File f = new File("xyz.txt");
int lineNumber = 666;
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
int count = -1;
try {
while((line = br.readLine())!=null){
count++;
if (count == lineNumber){
//get the line, do what you want
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
} catch (IOException e) {
br = null;
}
}
//do what you want with the line
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to write in file, I need to write total number of the record in first line, and in while loop write all other line, everything working good but, in first line need to write total number of the record how can i do that, Please help me!! Thanks!!
Here is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class headerline {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File folderall = new File("FilesIn1");
File[] BFFileall = folderall.listFiles();
for (final File file : BFFileall) {
String str = file.getName();
BufferedReader br = null;
BufferedWriter lbwp = null;
BufferedWriter lb = null;
try {
int lbwpcount = 1;
int lbcount = 1;
String reprintbwletterbwpca = (str);
lbwp = new BufferedWriter(new FileWriter(reprintbwletterbwpca));
lbwp.write("Total line number: " + lbwpcount);
String reprintbwletterbwpcalb = (str);
lb = new BufferedWriter(new FileWriter(reprintbwletterbwpcalb));
lb.write("Total line number: " + lbwpcount);
br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] actionID = line.split("|");
String actionid = actionID[2];
String custnumber = actionID[3];
lbwp.write("ActionID: " + actionid + ",CustomerNumber: " + custnumber + "\r\n");
lbwpcount++;
lb.write("ActionID: " + actionid + ",CustomerNumber: " + custnumber + "\r\n");
lbcount++;
}
lbwp.close();
lb.close();
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
}
suppose file has 1201 lines, it should print
Total line number: 1200, in first line.
than
"ActionID: " + actionid + ",CustomerNumber: " + custnumber
..........
suppose other file has 1451 lines, it should print
Total line number: 1450, in first line.
than
"ActionID: " + actionid + ",CustomerNumber: " + custnumber
..........
I have no idea how can i do that, please help me!! can i write first line as last after finish while loop??
Thanks in advanced!!
Simply use java.nio.file package. It has class Files which has a method readAllLines(...). This will read all lines and add it to a List. Simply use List.size() to get number of lines, and write it to another file as you wanted :-)
Try this program, this will let you know the number of lines in the file :
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.List;
public class ReadAndWriteFile {
private Path actualPath;
private Path sourcePath;
private BufferedReader reader;
private BufferedWriter writer;
private List<String> lines;
public ReadAndWriteFile() {
sourcePath = Paths.get("xanadu.txt");
//sourcePath = sourcePath.toAbsolutePath();
actualPath = Paths.get("xanadu_new.txt");
//targetPath = actualPath.toAbsolutePath();
Charset charset = Charset.forName("US-ASCII");
try {
lines = Files.readAllLines(sourcePath, charset);
System.out.println("Number of Lines : " + lines.size());
reader = Files.newBufferedReader(sourcePath, charset);
writer = Files.newBufferedWriter(actualPath, charset);
String message = "Total Line Number : " + lines.size();
writer.write(String.format("%s%n", message));
for (String line : lines) {
System.out.println(line);
writer.write(String.format("%s%n", line));
}
reader.close();
writer.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public static void main(String[] args) {
new ReadAndWriteFile();
}
}
Text File (xanadu.txt) Contents :
In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.
You can use Apache Commons FileUtils.readLines(). This returns you all lines in your original file as a list, from which you can get the size.
Otherwise you would have to read all the lines manually to count them first and then write them to the file.
Here's a high level explanation:
Loop through all the lines and store it in a List<Record>.
Write the total number of elements in your List<Record> as the first line (this will be total number of records)
In a loop, write the record data to the rest of the file
Since you need the total first, that means you've gotta loop once to find out what the total is. Then loop again to write the records.
You cannot know the total line number until you have read all the lines of the file.
Some options available to you are:
Read the file twice. The first time, simply keep a count the number of lines. Print it. Then read the file a second time, and write our the records like you are doing at the moment.
Hold the records in memory temporarily. As you read the file, keep the content in a collection (e.g. ArrayList) and write it out at the end. You can use list.size() to get the number of records. You could use use Apache Commons FileUtils.readLines() to do this, if you don't mind introducing a JAR dependency. EDIT: Or write your own method (see below).
Prepend the record count afterwards. Write out the file then as you are doing then prepend the record count to the file.
Challenge the requirements. Ask if it is really necessary to output the record count at the start? Could it be omitted? Could it be at the end? Etc.
Here's some sample code for option 2 - a method for reading the file into a list that you can manipulate:
public static List<String> readLines(File file) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
} finally {
br.close();
}
return lines;
}
You use it like this:
File file = new File("example.txt");
List<String> lines = readLines(file);
int lineCount = lines.size();
// TODO: Write out the line count
for (String line : lines) {
// TODO: Process the line
}