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]]*$", "");
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 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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
thanks to everyone in advance.
I have lines of strings input through a text file and would like to modify the output to remove the last two letters of each string. This is what the text file currently reads:
hello how are you
cool
i am amazing
and this is the code I'm using (from Java-tips.org)
package MyProject
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This program reads a text file line by line and print to the console. It uses
* FileOutputStream to read the file.
*
*/
public class FileInput {
public static void main(String[] args) {
File file = new File("MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The code works perfectly, but I'd like to modify the output to remove the last two letters of each string (string = one per line) Thanks everyone!
Here's my recommendation. Don't use streams for something so trivial and non-load intensive. Stick to the basics, use a Scanner and read your file line-by-line.
Here's the method to success!
Learn how to use a Scanner to read Strings from a text file line-by-line.
Make sure you split the Strings apart with the str.split() method accordingly.
Store each line's String value into a array/list/table.
Modify your stored Strings to remove the last two letters. Look into the str.subString(s,f) method.
Learn how to use a PrintWriter to output your modified Strings to a file.
Good luck!
Comment Reply
Read in a line as a String from texfile.
File file = new File("fileName.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine(); //<------This is a String representation of a line
System.out.println(line); //prints line
//Do your splitting here of lines containing more than 1 word
//Store your Strings here accordingly
//----> Go on to nextLine
}
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 concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Let's say I have a file that contains these information
1, 2, 3, 4
5, 6, 7, 8
now how can I ask the program to write ONLY 4 (which is the end of the first line) to a different file. But here's the trick, NOT depending on the user's input.
so after the program ends, the other file would contain
4
I tried trimming the Line (String=String1.trim()) and using the function endsWith() but I need to put a String inside these parentheses.
I started java 3 weeks ago, so please bear with me, thanks.
Use split()
String line = in.nextLine(); // read a line
String[] tokens = line.split("[\\s,]+"); // splits the line into an array
out.write(tokens[tokens.length - 1]); // print the last index of the array.
You can use the split() function to split a line on a separator into a String array. So:
String x = "1,2,3,4";
String[] split = x.split(",");
now the split array contains the individual items, and you can get the last one like this:
String last = split[split.length - 1];
Read the file, line by line
for each line, split the string (String.split()) with space and then access the last element in the array returned by split()
Write the element to the new File (see BufferedWriter and FileWriter).
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
if(line.Trim().endsWith( "4" )){
stringBuffer.append(line);
stringBuffer.append("\n");
}
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
// write the buffer content to new file.
File file = new File("newfile.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are two ways to do this:
The easy way: use myString.subString(myString.length()-1)
The complex/professional way (overkill for your case but just for reference): Use a regex pattern like this.
final String input = "1, 2, 3, 4";
final Pattern pattern = Pattern.compile("(.)\\s*$");
final Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
Where the pattern used means:
(.) - ()capture .any single char
\\s* - followed by 0 or more white-space chars
$ - followed by the end of 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
}