Not able to write on a file - java

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();
}

Related

Reading twice an InputStream throws IOException

I'm facing a problem, can someone tell me how to void this? It throws up an "java.io.IOException: Stream closed". I know where my mistake is but I dont know how to fix it. BufferedReader closes from the first function and I dont know how to reset it within the second one. Function should format text from one text file to another with tabs. Thank you
import java.io.*;
public class TestClass {
private void prosekStudentKRS(FileReader fr) throws IOException{
BufferedReader reader = null;
int j = 0, vksum = 0;
try{
reader = new BufferedReader(fr);
reader.readLine();
String line;
while((line = reader.readLine()) != null) {
int sum = 0;
j++;
String[] niza = line.split(",");
for(int i = 1; i < niza.length; i ++) {
sum+=Integer.parseInt(niza[i]);
}
vksum += Integer.parseInt(niza[1]);
System.out.printf("Student %d ima prosek %.2f\n", j, (float) sum / 3);
}
System.out.println("Prosek po KRS: " + vksum / (double) j);
} catch (Exception e){
e.printStackTrace();
} finally {
if(reader != null) {
reader.close();
}
}
}
private void TSV(FileReader fr, FileWriter fw) throws IOException {
BufferedReader reader = null;
BufferedWriter writer = null;
StringBuilder sb = null;
try {
reader = new BufferedReader(fr);
writer = new BufferedWriter(fw);
String line;
while ((line = reader.readLine()) != null) {
String[] niza = line.split(",");
sb = new StringBuilder();
for(int i = 0; i < niza.length; i ++) {
sb.append(niza[i] + "\t");
}
writer.write(sb.toString());
writer.newLine();
writer.flush();
}
} finally {
if (reader != null)
reader.close();
if(writer != null) {
writer.flush();
writer.close();
}
}
}
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("C:\\Users\\pc\\IdeaProjects\\LabOS01\\rezultaticsv.txt");
FileWriter fw = new FileWriter("C:\\Users\\pc\\IdeaProjects\\LabOS01\\rezultatitsv.txt");
TestClass filetest = new TestClass();
filetest.prosekStudentKRS(fr);
filetest.TSV(fr, fw);
}
}
Either create two distinct FileReader objects and pass a different to each method.
Otherwise you can also create a BufferedReader from the FileReader before invoking the methods, pass it to the first method, reset it with the reset() method and pass it to the other method.
As alternative if the file is not too big, you could store in a List<String> each line read rather than reading again the file.
It would be more efficient.

Based on condition txt file divided into two files in 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);
}
}

How to remove blank lines from a text file in java

I am trying to duplicate the original into a new file. In the new file I want the exact same things as the original BUT no blank lines.
Note: I looked at other posts and tried with no success.
Currently:
1
2
3
How I want it to be: -- no blank lines
1
2
3
Here is my code so far:
inputFileName = "x.txt";
outputFileName = "y.txt";
inputFile = new BufferedReader(new FileReader(inputFileName));
outputFile = new PrintWriter(new FileWriter(outputFileName));
String lineOfText = inputFile.readLine();
while(lineOfText != null)
{
if (lineOfText.isEmpty())
{
outputFile.print("null");
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
inputFile.close();
outputFile.close();
}
Thank you for all who can possibly help. I assumed that print("null") would print out 'nothing' but it indeed prints out null, I do not know how to print out 'nothing'.
You need to skip the println in case the line is empty:
while(lineOfText != null)
{
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
lineOfText = inputFile.readLine();
}
You're on the right track, but this
while(lineOfText != null)
{
if (lineOfText.isEmpty())
{
outputFile.print("null");
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
shouldn't be writing null on empty lines. I think you wanted something like
while(lineOfText != null)
{
if (!lineOfText.isEmpty())
{
outputFile.println(lineOfText);
}
lineOfText = inputFile.readLine();
}
Also, I suggest you use a try-with-resources Statement instead of manually managing your close(s). It's probably a good idea to trim (as suggested in the comments) before your test, and you can simplify your loop and you should limit variable visibility. All together like,
String inputFileName = "x.txt";
String outputFileName = "y.txt";
try (BufferedReader inputFile = new BufferedReader(new FileReader(inputFileName));
PrintWriter outputFile = new PrintWriter(new FileWriter(outputFileName))) {
String lineOfText;
while ((lineOfText = inputFile.readLine()) != null) {
lineOfText = lineOfText.trim();
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
}
}
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data1.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}

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