Retrieving a string by line number? Java [closed] - java

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
}
}

Related

How to replace a line with something? [closed]

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.

regular expression to replace anything but unicode letters in Java [closed]

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]]*$", "");

How to read data from file till I encounter an empty line [duplicate]

This question already has answers here:
How can I read a large text file line by line using Java?
(22 answers)
Closed 6 years ago.
Is there a way I can read multiple lines from a text file until I encounter an empty line?
For example my text file looks like this:
text-text-text-text-text-text-text-text-text-text-text-text-text-text-text-text
//This is empty line
text2-tex2-text2-tex2-text2-tex2-text2-text2
Now, I want to input text-text... till the empty line into a string. How can I do that?
check below code, 1st i have read all the lines from text file, then i have check whether file contains any blank line or not, if it contains then i break the loop.
A.text
text-text-text-text-text-text-text-text-text-text-text-text-text-text-text-text
text2-tex2-text2-tex2-text2-tex2-text2-text2
import java.util.*;
import java.io.*;
public class Test {
public static void main(String args[]){
try (BufferedReader br = new BufferedReader(new FileReader("E:\\A.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()){
System.out.println(line);
} else {
break;
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

Modifying Output in String Input By Text File (Java) [closed]

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
}

Writing only the end of the line in java [closed]

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

Categories

Resources