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();
}
}
}
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.
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"
What I wanted to do is convert an ArrayList to file and after that, use the file line per line.
My code:
List<String> Inserts = new ArrayList<String>();
String FileToLoad = null;
.
.
.
.
FileToLoad = prpfile.properties();
System.out.println(FileToLoad);
FileWriter writer = new FileWriter(FileToLoad);
for (String str : Inserts) {
writer.write(str);
}
writer.close();
String QueryNewData = "LOAD DATA LOCAL INFILE '" + FileToLoad + "' INTO TABLE companies FIELDS TERMINATED BY ',' (Name,Address,NumberDUG,post,status)";
UpdateDatabase LoadNewData = new UpdateDatabase();
LoadNewData.LoadQuery(QueryNewData);
Onces the code run, the file is created correctly but it's made the wholw ArrayLIst in one single line. How could inlude a new line for each element in the ArrayList?
Apart from the obvious things that are wrong with your code:
naming convention not followed
stream not closed in finally {}
...
You must remember that a simple writer does not magically append line feeds, you could wrap it in a printwriter which has a println() much like System.out or you could do as the other answer suggest (i.e.) add a line feed manually.
However for cross-platform reasons I would suggest:
writer.write(str + System.getProperty("line.separator"));
Wrap your FileWriter in a BufferedWriter. Javadoc. FileWriter has the newLine() method.
Other option is to write the new line using System.lineSeparator(), which is cross-platform.
if you really want to use it simple way than others suggested, you can use printwriter as it have println() method which takes string as parameter.
PrintWriter pw = new PrintWriter(FileToLoad);
for(int index=0;index<Inserts.size();index++)
{
pw.println(arrayList.get(index));
}
//pw.flush(); not needed since by default its enabled
Solution:
package com.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CreateFileFromList {
public static void main(String[] args) throws IOException {
List<String> list = new ArrayList<String>();
list.add("This is line 1.");
list.add("This is line 2.");
list.add("This is line 3.");
File f = new File ("C:\\temp\\Sample.txt");
if (!f.exists()) {
f.createNewFile();
}
FileWriter fw = new FileWriter(f.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for(String s : list) {
bw.write(s + System.getProperty("line.separator"));
}
bw.close();
}
}
New file Sample.txt will be created on c:\temp directory along with below contents:
This is line 1.
This is line 2.
This is line 3.
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is a code snippet but basically what I want to do is read from a file named 'listings.txt' and write to a file named 'overview.txt'. I want to take the information out of 'listings.txt' and put them into 'overview.txt' as is (I will figure out the rest later).
The file 'overview.txt' is created and appears to loop through the file 'listings.txt' and write to 'overview.txt'. However, once I open the file 'overview.txt' it is empty. Could someone go through a quick glance at my code and spot something erroneous?
package yesOverview;
import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class yesOverview {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String strInput = "foo.bar";
System.out.print("Please enter the listings file (the full path to the file): ");
strInput = input.next();
//This makes sure that the inputed file is listings.txt as required for KET1 task 2
while (strInput.contains("listings.txt") == false) {
System.out.print("Incorrect file. Please enter listings file(the full path to the file): ");
strInput = input.next();
}
infos(strInput);
input.close();
}
public static void infos(String strInput) {
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter the overview.txt file (the full path to the file): ");
String strInput2 = "foo.bar";
strInput2 = input2.next();
//This also makes sure that the overview.txt file is provided.
while (strInput2.contains("overview.txt") == false) {
System.out.print("Incorrect file. Please enter overview file(the full path to the file): ");
strInput2 = input2.next();
}
//Creates the file f then places it in the specified directory.
File f = new File(strInput2);
try {
//Creates a printerwriter out that writes to the output file.
PrintWriter out = new PrintWriter(strInput2);
} catch (FileNotFoundException ex) {
Logger.getLogger(KETTask2Overview.class.getName()).log(Level.SEVERE, null, ex);
}
//String that holds the value of the next line.
String inputLine = "";
//Creates the Buffered file reader / writer.
try {
BufferedReader in = new BufferedReader(new FileReader(strInput));
FileWriter fstream = new FileWriter(strInput2);
BufferedWriter out = new BufferedWriter(fstream);
while (in.readLine() != null) {
out.write(in.read());
}
in.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Try this
Close the BufferedWriter stream (ie out.close() )
try and use nextLine() instead of next(), as next() only takes in a single word, but for a complete line use nextLine(), though this doesnt seem to be the problem here.
What i do when i have to read and write to files, i normally follow these steps
For Reading from a file
File f = new File("my.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((br.readLine())!=null) {
// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}
br.close();
For Writing to a file:
Boolean isDone = true;
Scanner scan = new Scanner(System.in);
File f = new File("my.txt");
FileWriter fr = new FileWriter(f);
BufferedWriter br = new BufferedWriter(fr);
while (isDone) {
if (!isDone) {
br.write(new Scanner(System.in).nextLine());
}
}
public static long copy (Reader input, Writer output) throws IOException {
char[] buffer = new char[8192];
long count = 0;
int n;
while ((n = input.read( buffer )) != -1) {
output.write( buffer, 0, n );
count += n;
}
return count;
}
Usage Example:
copy( reader, new FileWriter( file ) );
You're not closing out.
The finally block for the writeList method cleans up and then closes the BufferedWriter.
finally {
if (out != null) {
System.out.println("Closing BufferedWriter");
out.close();
} else {
System.out.println("BufferedWriter not open");
}
}
I am writing a Java program that inputs a test file, performs some modifications to the data, then writes it to a new file output.
The input text file looks like this...
url = http://184.154.145.114:8013/wlraac name = wlr samplerate = 44100 channels =2 format = S16le~
url = http://newstalk.fmstreams.com:8080 name = newstalk samplerate = 22050 channels = 1 format = S16le
The program needs to be able to change the samplerate to 44100, and the channels to 1, if they don't already have these values. I would also remove the url and name pieces completely. After these changes, the new line needs to be written out to a different output text file.
So far, all my program can do is select a file and display the contents of the file to the user. Could someone please point me in the right direction for how my program should work
to achieve my required outcome.
As somebody asked here is what I have so far
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class reader2 {
public reader2() {
}
public static void main(String[] args) {
reader(args);
}
public static void reader(String[] args) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".txt")
|| f.isDirectory();
}
public String getDescription() {
return "Text Documents (.txt)";
}
});
int r = chooser.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getName();
String pathToFIle = chooser.getSelectedFile().getPath();
System.out.println(name);
try{
BufferedReader reader = new BufferedReader( new FileReader( pathToFIle ) ); //Setup the reader
while (reader.ready()) { //While there are content left to read
String line = reader.readLine(); //Read the next line from the file
String[] tokens = line.split( "url = " ); //Split the string at every # character. Place the results in an array.
for (String token : tokens){ //Iterate through all of the found results
//System.out.println(token);
System.out.println(token);
}
}
reader.close(); //Stop using the resource
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
You will need to do something like this ...
Read the contents of the file, one line at a time
Split the line up into the individual components, such as splitting it on the 'space' character
Change the sample rate and channel values according to your question
Write the line out to a file, and start again from step 1.
If you give this a try, post some code on StackExchange with any problems and we'll try to assist.
can you try
File file = new File( fileName );
File tempFile = File.createTempFile("buffer", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(br.ready()) {
String line = br.readLine();
String newLine = line.replaceAll( "samplerate =\\s*\\d+", "samplerate = 44100");
newLine = newLine.replaceAll( "channels =\\s*\\d+", "channels = 1");
fw.write(newLine + "\n");
}
fw.close();
br.close();
fr.close();
// Finally replace the original file.
tempFile.renameTo(file);
Ref: Files java replacing characters