Appending a string on the specific place in txt file - Java - java

I'am trying to append string(link) to the txt file on the specific place(In line where is "Link:"), to get line in file like "Link: www.link.something". I am using next code but my logic doesn't work.
if(file.getName().equals(filename+".txt")) {
link = line;
BufferedReader br;
BufferedWriter bw;
boolean no=false;
String lineE;
String data="Link:";
String lessonPath=link;
br = new BufferedReader(new FileReader(file));
while((lineE =br.readLine()) !=null){
if(!no){
data=line;
no=true;
}else{
data = data+"\n"+lineE;
}
}
bw = new BufferedWriter(new FileWriter(file));
bw.write(data+"\n"+lessonPath);
System.out.println(data+lessonPath);
bw.flush();
bw.close();
br.close();
}

If you can modify the text file then you could use StringSubstitutor to replace the template.

Related

Editing an already existing text file

I'm trying to edit an existing file that I had just created and so far I have no clue on how it's done.
Can anyone show me how and please explain line by line on what the code does?
import java.io.*;
public class Hey {
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Title");
String title = br.readLine();
File f = new File(title +".txt");
f.createNewFile();
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("What you want to input in the text");
String text = br.readLine();
bw.write(text);
bw.flush();
bw.close();
}
}
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
Creates a read buffer from the standard input.
String title = br.readLine();
Reads from this buffer until there's a return character sequence found ('\n', '\r' or "\r\n"). The entire line excluding the return sequence will be saved as title.
File f = new File(title +".txt");
Creates a File object with the name read from the console.
f.createNewFile();
Creates the file if it doesn't exist yet.
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
Creates a buffered writer to write into fw.
String text = br.readLine();
Again reads a line from the console.
bw.write(text);
Writes this line into the buffer.
bw.flush();
Ensures the whole buffer is flushed into the file (written into the file).
bw.close();
Closes the buffer of your buffered writer. You should also close the reader buffer br and the FileWriter fw.

FileInputStream only reads the first word in a file

I want to read words in file.txt file token by token and add a Part of Speech tag to each of them and write it to file2.text file. file.txt content is tokenized. So here's my code.
public class PoSTagging {
#SuppressWarnings("resource")
public static void PoStagMethod() throws IOException {
FileInputStream fin= new FileInputStream("C:\\Users\\dell\\Desktop\\file.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline=br.readLine();
System.out.println(strline+"first");
try{
POSModel model = new POSModelLoader().load(new File("en-pos-maxent.bin"));
PerformanceMonitor perfMon = new PerformanceMonitor(System.err, "sent");
POSTaggerME tagger = new POSTaggerME(model);
String input = strline;
#SuppressWarnings("deprecation")
ObjectStream<String> lineStream =new PlainTextByLineStream(new StringReader(input));
perfMon.start();
String line;
while ((line = lineStream.read()) != null) {
String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line);
String[] tags = tagger.tag(whitespaceTokenizerLine);
POSSample sample = new POSSample(whitespaceTokenizerLine, tags);
System.out.println(sample.toString()+"second");
//String t=sample.toString();
FileOutputStream fout=new FileOutputStream("C:\\Users\\dell\\Desktop\\file2.txt");
//fout.write(t.getBytes());
perfMon.incrementCounter();
fout.close();
}
perfMon.stopAndPrintFinalResult();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
When PoStagMethod() is invoked from another class, only the first word in file.txt file gets written into the file2.txt file. Why won't it read other words in the file? What is wrong with my code?
You can simply read the file.txt line by line using BufferedReader. Then process each line as you know with your POSModel, then write the outputs to the file2.txt using BufferedWriter. A snippet code as below might help:
POSModel model = new POSModelLoader().load(new File("en-pos-maxent.bin"));
PerformanceMonitor perfMon = new PerformanceMonitor(System.err, "sent");
POSTaggerME tagger = new POSTaggerME(model);
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\dell\\Desktop\\file2.txt"));
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\dell\\Desktop\\file.txt"));
String line = "";
while((line = bufferedReader.readLine()) != null){
String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line);
String[] tags = tagger.tag(whitespaceTokenizerLine);
// Do your work with your tags and tokenized words
bufferedWriter.write(/* the string which is needed to be written to your output */);
// for adding new-lines in the output file, uncomment the following line:
//bufferedWriter.newLine();
}
//Do not forget to flush() and close() the streams after your job is done:
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
If you could make this work, it's not bad to replace old-fashioned try-catch clause with try-with-resource which was added in java 1.7 to close the resources automatically.
Also If you need to write each word and it's tags in separated lines you may want to have an inner loop for writing to the file. It would be something like below:
POSModel model = new POSModelLoader().load(new File("en-pos-maxent.bin"));
PerformanceMonitor perfMon = new PerformanceMonitor(System.err, "sent");
POSTaggerME tagger = new POSTaggerME(model);
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\dell\\Desktop\\file2.txt"));
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\dell\\Desktop\\file.txt"));
String line = "";
while((line = bufferedReader.readLine()) != null){
String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line);
String[] tags = tagger.tag(whitespaceTokenizerLine);
for(String word: whitespaceTokenizerLine){
// Do your work with your tags and tokenized words
bufferedWriter.write(/* the string which is needed to be written to your output */);
// for adding new-lines in the output file, uncomment the following line:
//bufferedWriter.newLine();
}
}
//Do not forget to flush() and close() the streams after your job is done:
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
Hope this would be helpful,
Good Luck.

Java - Copy long text of a text file to another

I have one txt file with a very, very long text and I want to read, make some changes and copy that text to other txt files. The problem is that I can't read the file by the BufferedReader because I'd have to store the text in a variable, but that can't be done due to capacity and then write it to another file... Is there a way this can be done?
BuffereReader(Writer) works fine for this tasks (reading,writing large files)
BufferedWriter bw=null ;
BufferedReader br=null;
try{
br = new BufferedReader(new FileReader(new File("e:/temp/1.txt")));
bw = new BufferedWriter(new FileWriter(new File("e:/temp/2.txt")));
String st="";
while((st=br.readLine())!=null){
bw.write(st.replace("a","b"));
bw.newLine();
}
bw.close();
br.close();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
}

bufferedReader reads the filename only

I am building an android app where one of the functionality is that i write on a .txt file and late try to read it. Its very simple. But when I try to read the file using a BufferedReader it only gives me the name of the file and not the content withing.Below is my code(just the concerned portion)
File curFile = new File(getFilesDir().getAbsolutePath()+"/Notes/"+fileName);
BufferedReader br = new BufferedReader(new FileReader(curFile));
StringBuilder note = new StringBuilder(500);
String content;
while((content = br.readLine())!= null) {
ShowToast("Inside While: "+ content);//prints only fileName
note.append(content);
note.append('\n');
}
what is it that i am doing wrong?!

Java read in single file and write out multiple files

I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}

Categories