Read Specific Line and change String in that Line Java - java

I have a text file called "Hello.txt"
It has the following contents:
dog
cat
mouse
horse
I want to have a way to check that when reader is reading the lines, if the line equals 2, it replaces "cat" with "hen" and write back to the same file. I have tried this much so far and i dont know where to put the condition to check if line=2, then it does the replacing.My codes are:
import java.io.*;
public class Python_Read_Replace_Line
{
public static void main(String args[])
{
try
{
File file = new File("C:\\Hello.py");
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:\\Hello.txt")));
int numlines = lnr.getLineNumber();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + System.lineSeparator();
}
reader.close();
String newtext = oldtext.replaceFirst("cat", "hen");
FileWriter writer = new FileWriter("C:\\Hello.txt");
writer.write(newtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
The file contents should be something like this:
dog
hen
mouse
horse
The code I posted above works because it just replaces cat with hen. I want to have a condition (line number=2), then it replaces it.

Something like this?
int lineCount = 1;
while((line = reader.readLine()) != null)
{
if (lineCount == 2)
oldText += parseCommand.replaceFirst("\\w*( ?)", "hen\1")
+ System.lineSeparator();
//oldText += "hen" + System.lineSeparator();
else
oldtext += line + System.lineSeparator();
lineCount++;
}
Reference.

You could create a variable to keep track of which line number you are at, like so:
int line = 0;
while((line = reader.readLine()) != null)
if (line == 1)
{
oldtext += line + System.lineSeparator();
}
++line;
}

Related

how to read a specific line in .java file and prints out ...?

i am creating a project in which i need to read a specific line starting from a keyword in .java file .
i will have to read .java files for :
Intent myIntent = new Intent(StudentMap.this, StudentPref.class);
StudentMap.this.startActivity(myIntent);
how will i read these two lines anywhere in the code . should i have to set regex for this but how ?
i am using :
public void onClick(View v) {
TextView responseText = (TextView) findViewById(R.id.responseText);
String myData = "";
String test = "Intent ";
// String name="";
switch (v.getId()) {
case R.id.getExternalStorage:
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null){
myData = myData + strLine;
if (strLine.equals(test)) {
tv1.setText(tv1.getText() + strLine + "\n");
}
else{
tv1.setText(tv1.getText() + "nakaam" + "\n");
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
responseText.setText("MySampleFile.java data retrieved from external Storage...");
break;
}
tv1.setText(tv1.getText() + myData + "\n"+"\n"+"\n"+"end");
//tv1.setText(tv1.getText() + strLine + "\n");
}
as far my knowledge Intent keyword is static in every file so i can get the start of line like "Intent" but how to read this line and the next line only from large file..?
If you want to start your String at the Keyword Intent, and read a Number of Lines after that, you can do something like this:
try {
BufferedReader br = new BufferedReader(new FileReader(file));
int remainingLines = 0;
String stringYouAreLookingFor = "";
for(String line; (line = br.readLine()) != null; ) {
if (line.startsWith("Intent")) {
remainingLines = <Number of Lines you want to read after keyword>;
stringYouAreLookingFor += line
} else if (remainingLines > 0) {
remainingLines--;
stringYouAreLookingFor += line
}
}
}
I guess this should give you an idea on how to search the String you are looking for.

How to search for a word that is split in two lines?

I'm writing a program in java to search for a list of words(transaction numbers) in a .txt file. The .txt file can have any number of lines.
List<String> transactionList = new ArrayList<String>(
Arrays.asList("JQ7P00049", "TM7P04797", "RT6P70037");
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
try {
String readLine = bufferedReader.readLine();
for (String transactionIndex : transactionList) {
if (readLine != null) {
if (readLine.contains(transactionIndex)) {
System.out.println(transactionIndex + ": true");
readLine = bufferedReader.readLine();
} else {
readLine = bufferedReader.readLine();
}
}
}
}
The programs runs fine except if the word is split between two lines, for example:
-------- JQ7P0
0049----------
that's obviously because the bufferedReader reads line by line and does the comparison of search string with the content present in that line.
Is there any way to handle this scenario?
As durron597 mentioned, you weren't looping through the whole file, but here's a solution that assumes the file has at least 2 lines and that a transaction string doesn't span more than 2 lines.
It concatenates each line with the next, and searches for the strings in the concatenated lines. To prevent the same transaction from being printed twice, I added an additional check.
List<String> transactionList = new ArrayList<String>( Arrays.asList("JQ7P00049", "TM7P04797", "RT6P70037") );
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
try {
// Search the first line
String lastLine = bufferedReader.readLine();
for (String transactionIndex : transactionList) {
if (lastLine.contains(transactionIndex)) {
System.out.println(transactionIndex + ": true");
}
}
String currentLine = null;
// Search the remaining lines
while((currentLine=bufferedReader.readLine()) != null) {
String combined = lastLine + currentLine;
for (String transactionIndex : transactionList) {
if (currentLine.contains(transactionIndex) || (!lastLine.contains(transactionIndex) && combined.contains(transactionIndex))) {
System.out.println(transactionIndex + ": true");
}
}
lastLine = currentLine;
}
} catch ( Exception e ) {
System.out.println( e.getClass().getSimpleName() + ": " + e.getMessage() );
} finally {
bufferedReader.close();
}
This program has a second problem: You aren't going to read all the lines in longer files, because you have no loop that will loop through all the lines in the file.
That said, you can do this by reading two lines at once, and merging them together.
Here's a complete program:
private static final List<String> transactionList = new ArrayList<String>(Arrays.asList(
"JQ7P00049", "TM7P04797", "RT6P70037"));
public static void main(String[] args) throws Exception {
String filePath = "test.txt";
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
try {
String firstLine = bufferedReader.readLine();
String secondLine = bufferedReader.readLine();
if (secondLine == null) {
checkLine(firstLine);
}
do {
String combinedLine = firstLine + secondLine;
checkLine(combinedLine);
firstLine = secondLine;
} while ((secondLine = bufferedReader.readLine()) != null);
} finally {
}
}
private static void checkLine(String combinedLine) {
for (Iterator<String> iterator = transactionList.iterator(); iterator.hasNext();) {
String transactionIndex = iterator.next();
if (combinedLine.contains(transactionIndex)) {
System.out.println(transactionIndex + ": true");
iterator.remove();
}
}
}
Your code seems to not properly read the file, but rather reads as many lines as you have transaction numbers you're looking for. Assuming that this is not what you want, I have corrected it.
Also, I assume that an transaction number can span AT MOST two lines.
List<String> transactionList = new ArrayList<String>(
Arrays.asList("JQ7P00049", "TM7P04797", "RT6P70037"));
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String[] lastLines = {"",""};
try {
String readLine;
while((readLine = bufferedReader.readLine()) != null) {
lastLines[0] = lastLines[1];
lastLines[1] = readLine;
String combinedLastLines;
combinedLastLines = lastLines[0] + lastLines[1];
for (String transactionIndex : transactionList) {
if (combinedLastLines.contains(transactionIndex) && !lastLines[0].contains(transactionIndex)) {
System.out.println(transactionIndex + ": true");
}
}
}
}
The general idea is to always combine two lines, and look whether the transaction number is in there. Let's have a look at the code:
String[] lastLines = {"",""};
This line defines an array which we will use to store the two most recently read lines.
while((readLine = bufferedReader.readLine()) != null) {
This snippet reads as many lines as there are in your text file.
lastLines[0] = lastLines[1];
lastLines[1] = readLine;
String combinedLastLines;
combinedLastLines = lastLines[0] + lastLines[1];
This code is responsible for replacing the oldest line in the array, and push the currently readLine into the array. Those last two lines are then combined to one String!
if (combinedLastLines.contains(transactionIndex) && !lastLines[0].contains(transactionIndex)) {
Here we are searching the combined lines for the transaction numbers. But: when a transaction number is not spanning multiple lines, we might accidently find it twice. Therefore, the second check is for ensuring we did not find the transaction before.
Hope this is what you're looking for!

How to read records from a text file?

I tried this:
public static void ReadRecord()
{
String line = null;
try
{
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
line = br.readLine();
while(line != null)
{
System.out.println(line);
}
br.close();
fr.close();
}
catch (Exception e)
{
}
}
}
It non stop and repeatedly reads only one record that i had inputtd and wrote into the file earlier...How do i read records and use tokenization in reading records?
You have to read the lines in the file repeatedly in the loop using br.readLine(). br.readLine() reads only one line at time.
do something like this:
while((line = br.readLine()) != null) {
System.out.println(line);
}
Check this link also if you have some problems. http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Tokenization
If you want to split your string into tokens you can use the StringTokenizer class or can use the String.split() method.
StringTokenizer Class
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
st.hasMoreTokens() - will check whether any more tokens are present.
st.nextToken() - will get the next token
String.split()
String[] result = line.split("\\s"); // split line into tokens
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
line.split("\\s") - will split line with space as the delimiter. It returns a String array.
try this
while((line = br.readLine()) != null)
{
System.out.println(line);
}
Try This :
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
while((line=br.readline())!=null)
System.out.println(line);
For a text file called access.txt locate for example on your X drive, this should work.
public static void readRecordFromTextFile throws FileNotFoundException
{
try {
File file = new File("X:\\access.txt");
Scanner sc = new Scanner(file);
sc.useDelimiter(",|\r\n");
System.out.println(sc.next());
while (sc.hasNext()) {
System.out.println(sc.next());
}
sc.close();// closing the scanner stream
} catch (FileNotFoundException e) {
System.out.println("Enter existing file name");
e.printStackTrace();
}
}

How can i split a textfile and store 2 values in one line?

I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Remove last character/line

I have a snippet of code that prints text from a file to a JTextArea called textArea.
Unfortunately the method I'm using goes line by line (not ideal) and so I have to append each line with a \n
This is fine for now but a new line is created at the end.
The code I have is as follows:
class menuOpen implements ActionListener {
public void actionPerformed(ActionEvent e)
{
try {
File filePath = new File("c:\\test.txt");
FileInputStream file = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(file));
String displayText;
while ((displayText = br.readLine()) != null) {
textArea.append(displayText + "\n");
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Can anyone help me get rid of that last line?
how about:
text.substring(0,text.lastIndexOf('\n'));
(...)
FileReader r= new FileReader(filePath);
StringBuilder b=new StringBuilder();
int n=0;
char array[]=new char[1024];
while((n=r.read(array))!=-1) b.append(array,0,n);
r.close();
String content=b.toString();
textArea.setText(content.substring(0,content.lengt()-1);
(...)
Another idea:
boolean firstLine = true;
while ((displayText = br.readLine()) != null) {
if (firstLine) {
firstLine = false;
} else {
textArea.append("\n");
}
textArea.append(displayText);
}
The idea is to append a line break before the new line to display, except for the first line of the file.
The easiest way is to not use BufferedReader.readLine(). For example:
BufferedReader in = new BufferedReader(new FileReader(filePath));
char[] buf = new char[4096];
for (int count = in.read(buf); count != -1; count = in.read(buf)) {
textArea.append(new String(buf, 0, count));
}
EDIT
I should have seen this before, but a much better way is to let the JTextArea read the file:
BufferedReader in = new BufferedReader(new FileReader(filePath));
textArea.read(in, null);
This will still read in the newline at the end, but it will normalize all the line endings in your text (see the javadocs for DefaultEditorKit for an explanation of how line endings are handled). So you can get rid of the trailing newline with something like this:
// line endings are normalized, will always be "\n" regardless of platform
if (textArea.getText().endsWith("\n")) {
Document doc = ta.getDocument();
doc.remove(doc.getLength() - 1, 1);
}
How about
if (textArea.length > 0) textArea.Text = textArea.Text.Substring(0 ,textArea.Text.Length - 1)
Apparently you want a newline between two lines, not after each line. This means you should have at least two lines:
if (d = br.readLine()) != null ) {
textArea.append(displayText);
while (d = br.readLine()) != null ) {
textArea.append( "\n" + displayText);
}
}
Of course, it looks more complex. That's because 'between' is more complex than 'after'.
In your loop:
while ((displayText = br.readLine()) != null) {
if (textArea.length() > 0)
textArea.append("\n");
textArea.append(displayText);
}
i.e. if there is already some text in your textarea, insert a newline.
Its quite easy.. You just need to tweak your code a bit.
String displayText = br.readLine();
textArea.append(displayText);
while ((displayText = br.readLine()) != null) {
textArea.append("\n" + displayText);
}
I believe this code produce your desired function at minimum cost.

Categories