This question already has answers here:
Bufferedwriter works, but file empty?
(4 answers)
Closed 6 years ago.
I was trying to append a text in text file. I am using some new classes added in Java 7. But with my code nothing is added in text file. I have tried some debugging but not getting why it is not writing a text in file.
Here is a code:
public void input(String path, PrintWriter out) throws FileNotFoundException, IOException
{
String finalstring;
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Path FILE_PATH = Paths.get("C:/10", "tweets_6.txt");
BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
String line;
while((line = br.readLine()) != null)
{
finalstring = line;
URLEntity u;
finalstring = finalstring.replaceAll("https?://\\S+\\s?", "");
finalstring=finalstring.replace("#engineeringproblems", " ");
finalstring=finalstring.replace("#", " ");
// Stemming Algorithm
StringTokenizer st = new StringTokenizer(finalstring);
String finalstring1;
finalstring = "";
while (st.hasMoreTokens())
{
KrovetzStemmer ks = new KrovetzStemmer();
finalstring1 = ks.stem(st.nextToken());
// repeated characters remover
finalstring1 = finalstring1.replaceAll("(.)\\2{2,}", "$2");
FileInputStream in1 = new FileInputStream("C:\\10\\NonWords.txt");
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
FileInputStream in2 = new FileInputStream("C:\\10\\StopWords.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String line1;
String line2;
while((line1 = br1.readLine()) != null)
{
if(finalstring1.equals(line1))
{
finalstring += finalstring1 + " ";
}
}
while((line2 = br2.readLine()) != null)
{
if(finalstring1.equals(line2))
{
finalstring += finalstring1 + " ";
}
}
}
writer.write(finalstring);
writer.newLine();
}
}
Please suggest a change in my code. Something I am missing here.
You're using a writer, and they need to be closed. On top of that, you're using a BufferedWriter so you won't necessarily see any output before it's closed.
Related
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++;
}
}
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();
}
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();
}
}
I've a text file which contains text as:
VOLT=367
CURRENT=0.07
TEMP=031
RPM=3780
63HZ
VOLT=288
CURRENT=0.00
TEMP=030
RPM=3420
57HZ
and so on....
I want to take this text file as input in java and create an output text file having this text arranged as:
367,0.07,031,3780,63
288,0.00,030,3420,57
and so on until the end of txt file..
Coding attempt so far:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
try {
FileInputStream fstream = new FileInputStream("file path\data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
BufferedWriter brw = new BufferedWriter(new OutputStreamWriter(out));
do {
for (int i=1;i<50;i++) {
//I dont know what to do here
...
Try this,
String input = "";
br = new BufferedReader(new FileReader(inputFile));
out = new PrintWriter(outputFile);
StringBuilder result = new StringBuilder();
while ((input = br.readLine()) != null)
{
if(input.contains("HZ"))
{
result.append(input.replace("HZ", ""));
result.append("\n");
}
else
{
result.append(input.substring(input.indexOf("=") + 1, input.length()));
result.append(",");
}
}
System.out.println("result : "+result.toString());
Use this simple code.
String res="";
while ((input = br.readLine()) != null)
{
if(input.indexOf("=")!= -1){
res+=input.split("=+")[1]+",";
}
else{
res+="\n";
}
}
System.out.println("result : "+res.substring(0,res.length()-1));//To omit last ','
How do you replace a line in a text file?
For example you have 1.###
and want to replace it with 1.###
I have program this prgram at the moment.
You search through a list and if you find a string, that you want. You write the string to another file. My porblem is that I don't know how to replace a line in an existing text file.
private static BufferedReader br;
public static void main(String[] args) throws Exception{
try{
FileInputStream fstream = new FileInputStream("C:\\Users\\Timmic\\workspace\\Foutverbeterende codes\\genereren append testbinair apart.txt");
br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String tokens[] = strLine.split(";");
int x = Integer.parseInt(tokens[2]);
if(x<2){
tokens[3]="###";
String a1 = Arrays.toString(tokens);
String a2 = a1.replaceAll(" ", "");
String a3 = a2.replaceAll(" ", "");
String a6 = a3.replaceAll(",", ";");
String a7 = a6.replaceAll("[<>\\[\\],-]", "");
String a8 = a7 + ";";
System.out.println(a8);
FileWriter fwriter = new FileWriter("d is 2.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);
outputFile.println(a8);
outputFile.close();
}
}
}
catch(Exception e){}
}
and this is the list.
0; 000;0;*;0;0;0;
1; 001;1;*;0;0;1;
2; 010;1;*;0;1;0;
3; 011;2;*;0;1;1;
4; 100;1;*;1;0;0;
5; 101;2;*;1;0;1;
6; 110;2;*;1;1;0;
7; 111;3;*;1;1;1;
// it's okay to throw Exception in main, but ONLY during testing. NEVER EVER
// in production code!
public static void main(String[] args) throws Exception{
FileWriter fwriter = null;
FileInputStream fstream = null;
try {
fstream = new FileInputStream("C:\\Users\\Timmic\\workspace\Foutverbeterende codes\\genereren append testbinair apart.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
// this has to be moved OUT of the loop.
fwriter = new FileWriter("d is 2.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String tokens[] = strLine.split(";");
int x = Integer.parseInt(tokens[2]);
if(x<2){
tokens[3]="###";
String replaced = Arrays.toString(tokens)
.replaceAll(" ", "");
.replaceAll(" ", "");
.replaceAll(",", ";");
.replaceAll("[<>\\[\\],-]", "");
replaced += ";";
System.out.println(replaced);
outputFile.println(replaced);
}
}
// finally makes sure, that this block is executed, even if something
// goes wrong.
} finally {
if (fstream != null)
fstream.close();
if (fwriter != null)
fwriter.close();
}
}