Based on condition txt file divided into two files in java - java

My target is i have one txt file it contains some line of text. in this i have two words i.e A and 1. if line has "A" letter then next lines goto one file until next line contain "1" and if line contain "1" then next lines goto other file until "A" find.
Input file like follows
A
rahu
pahdu
jhaani
1
hjsdh
dhj
A
jiko
raju
A
tenk
kouou
I am expecting output
A.txt contain
rahu
pahdu
jhaani
Same
1.txt
My code
{
fis = new FileInputStream("E:\\Input.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
if(line.contains("LETTER00~VSAQCCCC~H~")) {
line = reader.readLine();
System.out.println(line);
}
else {
line= reader.readLine();
}
}
}

You could just repoint your FileOutputStream whenever you find a 1 or A.
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("in.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fosA = new FileOutputStream("out_A.txt");
FileOutputStream fos1 = new FileOutputStream("out_1.txt");
FileOutputStream fos = null;
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while (line != null) {
System.out.println(line);
if(line.equals("A"))
{
fos = fosA;
line = reader.readLine();
continue;
}
if(line.equals("1"))
{
fos = fos1;
line = reader.readLine();
continue;
}
fos.write(line.getBytes());
fos.write('\n');
fos.flush();
line = reader.readLine();
}
fos.close();
fosA.close();
fos1.close();
}

You can do something like this.
System.out.println("Reading File line by line using
BufferedReader");
String inputFIle = "";
String line;
boolean flag = false;
// String line = reader.readLine();
while ((line = reader.readLine()) != null) {
if (line.trim().equalsIgnoreCase("A")) {
inputFIle = "A.txt";
} else if(line.trim().equalsIgnoreCase("1")){
inputFIle = "1.txt";
}
else{
write(line, inputFIle);
}
}

You can do something like this
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new FileReader("Input.txt"));
boolean isFound = false;
List<String> main_list = new ArrayList<>();
List<String> sub_list = new ArrayList<>();
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains("A")) {
isFound = true;
} else if(line.contains("1")) {
isFound = false;
for (String aSub_list : sub_list) {
main_list.add(aSub_list);
}
sub_list.clear();
}
if(isFound && !line.contains("A")) {
sub_list.add(line);
}
}
for (String aMain_list : main_list) {
System.out.println(aMain_list);
}
}

Related

Issue in a while loop with my BufferedReader

I've a little issue with my script function.
To set the context, I want to create a loop so that it modifies a text document little by little, in relation to what the user enters in the console.
My text document is written so that several "INSERT" entries are listed, and the user can replace them two by two with the text of his choice.
But the problem is the following: the String arraylist content remains empty, that logically causes an error on the 16th line, because there is a problem with the BufferedReader (the String line is systematically null, because of a Strem error).
How can I solve this ?
The code is the following :
public void script() {
while(index*5 <= array.size()) {
List<String> content = new ArrayList<>();
int modificater = 1;
int position = (((index-1)*5)+4);
FileInputStream fIS= new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fIS, "UTF-8"));
String line = reader.readLine();
while(line != null) {
content.add(line);
line = reader.readLine();
}
System.out.println(content.get(position - 1));
Scanner enter = new Scanner(System.in);
String answer = enter.nextLine();
while(modificater < 3) {
for(String str : content) {
if(str.contains("INSERT")) {
str.replace("INSERT", answer);
modificater++;
}
}
}
reader.close();
FileWriter writer = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(writer);
for(String str : content) {
bw.write(str);
bw.newLine();
}
writer.close();
index++;
}
}
Here is an error that I have :
Exception in thread "main" java.io.IOException: Stream closed
at java.base/sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:51)
at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:124)
at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:208)
at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:120)
at java.base/java.io.BufferedWriter.close(BufferedWriter.java:268)```
Try changing your reader below your writer.close() and close your bw.
public void script() {
while(index*5 <= array.size()) {
List<String> content = new ArrayList<>();
int modificater = 1;
int position = (((index-1)*5)+4);
FileInputStream fIS= new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fIS, "UTF-8"));
String line = reader.readLine();
while(line != null) {
content.add(line);
line = reader.readLine();
}
System.out.println(content.get(position - 1));
Scanner enter = new Scanner(System.in);
String answer = enter.nextLine();
while(modificater < 3) {
for(String str : content) {
if(str.contains("INSERT")) {
str.replace("INSERT", answer);
modificater++;
}
}
}
FileWriter writer = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(writer);
for(String str : content) {
bw.write(str);
bw.newLine();
}
reader.close();
bw.close();
writer.close();
index++;
}
}

Not able to write on a file

The above is a working code snippet. The code runs fine but it does not write what is inside the else if(line.contains("{NEW_LIMIT}")) statement.
Another problem is that after the program writes into a new text file it loses its original format, as in to say it just writes everything in a single line.
Is there anything I am doing wrong?
public static void replace1(String name, String limit, String nlimit) throws IOException
{
File infile = new File("s://BlackBuck/Question_1_Template.txt");
File outfile = fileReturn();
FileWriter fw;
BufferedWriter bw = null;
FileReader fr;
BufferedReader br = null;
String line, putdata = null;;
try {
fr = new FileReader(infile);
br = new BufferedReader(fr);
fw = new FileWriter(outfile);
bw = new BufferedWriter(fw);
while((line = br.readLine()) != null)
{
if(line != null)
{
if(line.contains("{CUSTOMER_NAME}"))
{
putdata = line.replace("{CUSTOMER_NAME}", name);
bw.write(putdata);
}
else if(line.contains("{CURRENT_LIMIT}"))
{
putdata = line.replace("{CURRENT_LIMIT}", limit);
bw.write(putdata);
}
else if(line.contains("{NEW_LIMIT}"))
{
putdata = line.replace("{NEW_LIMIT}", nlimit);
bw.write(putdata);
}
else
{
bw.write(line);
}
}
}
}finally {
bw.close();
br.close();
}
}
If a line contains {CUSTOMER_NAME} or {CURRENT_LIMIT}, then statements {NEW_LIMIT} won't be run. You can simply fix this using following codes:
if(line != null) {
putdata = line.replace("{CUSTOMER_NAME}", name)
.replace("{CURRENT_LIMIT}", limit)
.replace("{NEW_LIMIT}", nlimit);
bw.write(putdata);
// append a line separator to current line
bw.newLine();
}

Saving text file content to a linked list

I am trying to save the contents of a word file line by line into a LinkedList.
What am I doing wrong? The console is showing that it is definatley reading the file but not saving its contents?
public class SpellCheck {
LinkedList<String> lines = new LinkedList();
boolean suggestWord ;
public static void main(String[] args) throws java.io.IOException{
System.out.println("Welcome to the spellchecker");
LinkedList<String> list = new LinkedList<String>();
try {
File f = new File("input/dictionary.txt");
FileReader r = new FileReader(f);
BufferedReader reader = new BufferedReader(r);
String line = null;
String word = new String();
while((line = reader.readLine()) != null)
{
list.add(word);
word = new String();
}
reader.close();
}catch(IOException e) {
e.printStackTrace();
}
for(int i = 0; i<list.size();i++){
System.out.println(list.get(i));
}
}
}
You are adding word which is an empty string instead of adding line which you read from file:
String word = new String();
while((line = reader.readLine()) != null)
{
list.add(word);
^^^^^
word = new String();
}
It should be:
while((line = reader.readLine()) != null) {
list.add(line);
}

How to display all lines of text from a file instead of stopping at the end of a line?

The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.
private String GetPhoneAddress() {
File directory = Environment.getExternalStorageDirectory();
File myFile = new File(directory, "mythoughtlog.txt");
//File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
if (!myFile.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
String line = br.readLine();
if (line == null) {
return null;
}
StringBuilder retVal = new StringBuilder(line);
line = br.readLine();
while (line != null) {
retVal.append(System.lineSeparator()).append(line);
line = br.readLine();
}
return retVal.toString();
}
if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
A considerably less verbose solution:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
StringBuilder retVal = new StringBuilder();
while ((line = br.readLine()) != null) {
retVal.append(line).append(System.lineSeparator());
}
return retVal.toString();
}

Output only giving me one line

Can anyone point me in the right direction here. I have a method that is supposed to read a file and display the data in that file. I can only get it to display one line. I know it is something simple I am over looking, but my brain is mush and I just keep digging a bigger hole.
public static String readFile(String file) {
String data = "";
if (!new java.io.File(file).exists()) {
return data;
}
File f = new File(file);
FileInputStream fStream = null;
BufferedInputStream bStream = null;
BufferedReader bReader = null;
StringBuffer buff = new StringBuffer();
try {
fStream = new FileInputStream(f);
bStream = new BufferedInputStream(fStream);
bReader = new BufferedReader(new InputStreamReader(bStream));
String line = "";
while (bStream.available() != 0) {
line = bReader.readLine();
if (line.length() > 0) {
if (line.contains("<br/>")) {
line = line.replaceAll("<br/>", " ");
String tempLine = "";
while ((tempLine.trim().length() < 1)
&& bStream.available() != 0) {
tempLine = bReader.readLine();
}
line = line + tempLine;
}
buff.append(line + "\n");
}
}
fStream.close();
bStream.close();
bReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buff.toString();
}
String line = null;
while ((line = bReader.readLine())!=null)
How about doing this with Guava:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html
List<String> lines = Files.readLines("myFile.txt", Charset.forName("UTF-8"));
System.out.println(lines);
You'd still have to do a little bit of work to concatenate the <br> lines etc...

Categories