What I'm trying to achieve is a program that makes a file from the template called WaarschuwingsBriefTemplate.txt (WarningLetterTemplate).The method is called with a Klant (Customer) in its parantheses.
Now when I call this method, it won't write any enters at all, even though there are enters in the Template and I'm trying to add enters in the method itself but it doesnt seem to work. Brief translation of the foreign words:
NAAM = NAME
ADRES = ADDRESS
POSTCODE = ZIP CODE
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileMaker {
public FileMaker(){
}
public void maakWaarschuwingsBrief(Klant k) throws IOException{
File file = new File("WaarschuwingsBriefTemplate.txt");
String newFile = "";
try{
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
String line = sc.nextLine();
if(line.contains("--NAAM--")){
line = line.replace("--NAAM--", k.getNaam())+"\n";
}
if(line.contains("--ADRES--")){
line = line.replace("--ADRES--", k.getAdres())+"\n";
}
if(line.contains("--POSTCODE--")){
line = line.replace("--POSTCODE--", k.getPostcode())+"\n";
}
newFile += line + "\n";
}
sc.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
File file2 = new File(k.getNaam().replaceAll("\\s","")+".txt");
if(!file2.exists()){
file2.createNewFile();
}
FileWriter fw = new FileWriter(file2.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(newFile);
bw.close();
}
}
`
If your template is not too big and it's ok to read the file as whole to memory maybe try https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html instead of manual manipulation?
Also use http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#lineSeparator-- instead of "\n"
Related
It couldnt replace the new word and place it in a new file.
I want to create a method that take 4 parameters, one with oldfile , one with new file, one with old word and one with new word and they are all of type string.
I also want to make it so that he case of the first letter the oldWord should be maintained when writing to the in the newFile, e.g. if oldWord was “Hit” and newWord was “Cab” then if “Hit” is found in the oldFile then “Cab” should be written to the newFile.
Im not allowed to use advanced java stuff like hashkeys and all that. Hope that enough infomaton and thank you in advance.
My code couldnt print the new words into the new file instead it just prints 4 more lines of the new words in the old file.
//////
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class part2d {
public static void main(String[] args)
{
modifyFile("test.txt","modify.txt", "Hit", "Cab");
System.out.println("done");
}
static void modifyFile(String oldfile, String newfile, String oldString, String newString)
{
File fileToBeModified = new File("modify.txt");
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String newContent = oldContent.replaceAll(oldString, newString);
writer = new FileWriter(fileToBeModified,true);
writer.write(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Both your reader and your writer are using the fileToBeModified variable. This variable is being set to modify.txt statically for both, so you're not actually reading and writing a new file, instead you're reading then appending the same file content again.
Think about what file you're creating using the BufferedReader/FileReader and the FileWriter, and consider how these are being set.
Good Morning. Having trouble with a parser using split method. Goal is to read in txt file, extract should statements, then write a new txt file with those should statements. I have it working when the text is on one continuous line. If I have a new line in the txt file, rewrites the file with just the last line. Possibly the structure of my loops? Also any suggestions for saving new file from the directory in which it was opened? Thank you
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/*This Program Will launch a File Explorer.
User will then chose a .txt file to be parsed.
A new file will be created labeled "Parsed_(Document Name)".*/
public class Parser {
#SuppressWarnings("resource")
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
Scanner userFile = new Scanner(System.in);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName() + "\n");
File file = new File(chooser.getSelectedFile().getName());
String newFile = ("Parsed_" + file);
userFile = new Scanner(file);
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
List<String> ShouldArray = new ArrayList<String>();
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should"))
ShouldArray.add(shouldStatements);
}
FileWriter writer = new FileWriter(newFile);
BufferedWriter bw = new BufferedWriter(writer);
for (String shallStatements : ShouldArray) {
System.out.println(shallStatements);
bw.append(shallStatements);
bw.newLine();
}
System.out.println("\nParsed Document Created: " + newFile);
JOptionPane.showMessageDialog(null, "Parsed Document Created: " + newFile);
bw.close();
writer.close();
}
userFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Test file 1 (works!)
Hello all. Here is a a packing list. You Should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet!
Test file 1 output:
You Should have a toothbrush
You Should have a Phone charger
And you definitely should have your wallet
Test file 2 (Only printing last line)
Hello all. Here is a a packing list. You Should have a toothbrush. You Should have a Phone charger.
Here is some random text to show the parser will not include this.
You definitely should have your wallet!
test file 2 output:
You definitely should have your wallet
You need to create your result array outside of the loop
/** Placed here**/
List<String> ShouldArray = new ArrayList<String>();
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
/** REMOVED HERE **/
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should"))
ShouldArray.add(shouldStatements);
}
......
otherwise you will only gather the results of your last loop.
Basically what your code was doing:
cut up file in lines
take each line
take next line
make a result board.
write results on board
take next line
erase board
write results on board
take next line
erase board
write results on board
and then at the end there is only a limited resultset on your board
You are overriding your Arraylist within the loop, however you don't actually need it
File file = chooser.getSelectedFile();
System.out.println("You chose to open this file: " + file.getName() + "\n");
String newFile = "Parsed_" + file.getName();
// open all closable objects using try-with-resources
try (Scanner userFile = new Scanner(file);
BufferedWriter bw = new BufferedWriter(new FileWriter(newFile))) {
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
for (String s : sentences) {
if (s.contains("Should") || s.contains("should")) {
System.out.println(s);
bw.append(s);
bw.newLine();
}
}
System.out.println("\nParsed Document Created: " + newFile);
JOptionPane.showMessageDialog(null, "Parsed Document Created: " + newFile);
// bw.close(); // not needed anymore
I've refactored the code, removing the "ShouldArray", which is not needed.
Pseudocode
While there are lines to read in the In file
Read each line
Split each line into Array of sentences
Loop through each sentence
If each sentence contains Should or should Then
Write sentence to Out file
End If
End Loop
End While
Close Out file
Close In file
The code below works with:
Multi line:
Hello all. Here is a a packing list.
You Should have a toothbrush. You Should have a Phone charger.
Here is some random text to show the parser will not include this.
You definitely should have your wallet!
Single line:
Hello all. Here is a a packing list. You Should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet!
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
public class ShouldStringsParser {
public ShouldStringsParser(String inFile, String outFile) throws IOException {
File file = new File(inFile);
FileWriter writer = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(writer);
Scanner userFile;
userFile = new Scanner(file);
String[] sentences;
while (userFile.hasNextLine()) {
String line = userFile.nextLine();
System.out.println(line);
sentences = line.split("\\.|\\?|\\!|\\r");
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should")) {
System.out.println(">>>" + shouldStatements);
bw.append(shouldStatements);
bw.newLine();
}
}
}
bw.close();
writer.close();
userFile.close();
}
public static void main(String[] args) {
try {
new ShouldStringsParser("inDataMultiLine.txt", "outDataMultiLine.txt");
new ShouldStringsParser("inDataSingleLine.txt", "outDataSingleLine.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read and write the text.
In read and write text file i have to print all the data in the text file but it print only the last line how to get all line write.
Program:
public class fs
{
try
{
BufferReader in = new BufferReader(FileReader(C:/Users/madhan kumar/Desktop/read.txt));
String s;
String[] result=null;
while((s=in.readLine())!=null)
{
result=s.split("\\|");
result = String[4];
String Name = result[0];
String age = result[1];
String Sex = result[2];
String field = result[3];
System.out.println("Name :"+Name+"Age :"+age+"Sex :"+Sex+"Field"+field);
BufferedWriter bw =new BufferedWriter (new FileWriter ("out.txt");
bw.write ("Name :"+Name+"Age :"+age+"Sex :"+Sex+"Field"+field);
Bw.close ();
}}
catch(Exception e)
{
System.out.println(e);
}
}
}
My txt file
malik|23|male|student
nakul|30|male|student
ram|27|male|worker
mak|25|male|student
The answer to your main question is that you only see the last line because you create a new BufferedWriter every time you write out to the .txt, and when you do that it deletes text already on the .txt file. To solve this problem simply declare your BufferedWriter outside of the while loop:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.FileReader;
import java.io.FileWriter;
public class fs{
public static void main(String[] args){
StringTokenizer str;
try
{
BufferedReader in = new BufferedReader(new FileReader("C:/Users/madhan kumar/Desktop/read.txt"));
BufferedWriter bw = new BufferedWriter (new FileWriter("out.txt"));
String s;
while((s=in.readLine())!=null){
str = new StringTokenizer(s, "|");
String name = str.nextToken();
String age = str.nextToken();
String sex = str.nextToken();
String field = str.nextToken();
System.out.println("Name: "+name+"\tAge: "+age+"\tSex: "+sex+"\tField: "+field);
bw.write("Name: "+name+"\tAge: "+age+"\tSex: "+sex+"\tField: "+field);
}
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
I made a few small adjustments, largest being that I used StringTokenizer which does pretty much the same thing as your splitting method, but is a little more eloquent.
I have an input file like below. An input file contains list of 8 digit numbers separated by comma. For that we need to read input file mentioned below.
12345678,
12345679,
12345680,
12345681,
12345682,
12345683,
12345684,
12345685
as i have to read the above file. I need to insert first value after -d= sequence,second value at -d= sequence and so on...
finally output file must be:
D:\data\12345678.pdf -d=12345678
D:\data\12345679.pdf -d=12345679
D:\data\12345680.pdf -d=12345680
D:\data\12345681.pdf -d=12345681
D:\data\12345682.pdf -d=12345682
D:\data\12345683.pdf -d=12345683
here path and file name varies.but main goal is to insert those values after the -d= sequence of every line only.
How can i achieve this?
Thanks for any help
One way to accomplish this is
package com.test.file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;
public class OutputGenerator {
private static final String PATH = "D:\\data\\";
private static final String FORMAT = PATH + "{0}.pdf -d={0}";
public static void main(String[] args) throws IOException {
String inputFile = "/Users/chatar/Documents/dev/projects/weekend-practice/stack-overflow/src/com/test/file/input.txt";
String outputFile = "/Users/chatar/Documents/dev/projects/weekend-practice/stack-overflow/src/com/test/file/output.txt";
FileReader reader = new FileReader(new File(inputFile));
BufferedReader bufferedReader = new BufferedReader(reader);
FileWriter writer = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
try {
while(bufferedReader.readLine() != null) {
String inputLine = bufferedReader.readLine();
System.out.println("inputline :: "+ inputLine);
inputLine = inputLine.replaceAll("\\s+", "").replace(",", "");
MessageFormat format = new MessageFormat(FORMAT);
String outputLine = format.format(new Object[] {inputLine});
bufferedWriter.write(outputLine);
bufferedWriter.newLine();
}
}
finally {
bufferedReader.close();
bufferedWriter.close();
}
}
}
I'm trying to write some text to a file. I have a while loop that is supposed to just take some text and write the exact same text back to the file.
I discovered that the while loop is never entered because Scanner thinks there's no more text to read. But there is.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
String whatToWrite = "";
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
PrintWriter output = new PrintWriter(theFile);
while (readinput.hasNext()) { //why is this false initially?
String whatToRead = readinput.next();
whatToWrite = whatToRead;
output.print(whatToWrite);
}
readinput.close();
output.close();
}
}
The text file just contains random words. Dog, cat, etc.
When I run the code, text.txt becomes empty.
There was a similar question: https://stackoverflow.com/questions/8495850/scanner-hasnext-returns-false which pointed to encoding issues. I use Windows 7 and U.S. language. Can I find out how the text file is encoded somehow?
Update:
Indeed, as Ph.Voronov commented, the PrintWriter line erases the file contents! user2115021 is right, if you use PrintWriter you should not work on one file. Unfortunately, for the assignment I had to solve, I had to work with a single file. Here's what I did:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> theWords = new ArrayList<String>();
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
while (readinput.hasNext()) {
theWords.add(readinput.next());
}
readinput.close();
PrintWriter output = new PrintWriter(theFile); //we already got all of
//the file content, so it's safe to erase it now
for (int a = 0; a < theWords.size(); a++) {
output.print(theWords.get(a));
if (a != theWords.size() - 1) {
output.print(" ");
}
}
output.close();
}
}
PrintWriter output = new PrintWriter(theFile);
It erases your file.
You are trying to read the file using SCANNER and writing to another file using PRINTWRITER,but both are working on same file.PRINTWRITER clear the content of the file to write the content.Both the class need to work on different file.