Modify contents of text file and write to new file in java - java

So I've got the basic code for this however due to the while loop I'm using, I can really only write the last line of the text file to the new file. I'm trying to modify the text from testfile.txt and write it to a new file named mdemarco.txt. The modification I'm trying to do is add a line number in front of each line. Does anybody know a way to maybe write the contents of the while loop to a string while it runs and output the resulting string to mdemarco.txt or anything like that?
public class Writefile
{
public static void main(String[] args) throws IOException
{
try
{
Scanner file = new Scanner(new File("testfile.txt"));
File output = new File("mdemarco.txt");
String s = "";
String b = "";
int n = 0;
while(file.hasNext())
{
s = file.nextLine();
n++;
System.out.println(n+". "+s);
b = (n+". "+s);
}//end while
PrintWriter printer = new PrintWriter(output);
printer.println(b);
printer.close();
}//end try
catch(FileNotFoundException fnfe)
{
System.out.println("Was not able to locate testfile.txt.");
}
}//end main
}//end class
The input file text is:
do
re
me
fa
so
la
te
do
And the output I'm getting is only
8. do
Can anybody help?

The String variable b is overwriten in each iteration of the loop. You want to append to it instead of overwriting (you may also want to add a newline character at the end):
b += (n + ". " + s + System.getProperty("line.separator"));
Better yet, use a StringBuilder to append the output:
StringBuilder b = new StringBuilder();
int n = 0;
while (file.hasNext()) {
s = file.nextLine();
n++;
System.out.println(n + ". " + s);
b.append(n).append(". ").append(s).append(System.getProperty("line.separator"));
}// end while
PrintWriter printer = new PrintWriter(output);
printer.println(b.toString());

Your content on each line of text didn't saved. So only the last line displays on the output file. Please try this:
public static void main(String[] args) throws IOException {
try {
Scanner file = new Scanner(new File("src/testfile.txt"));
File output = new File("src/mdemarco.txt");
String s = "";
String b = "";
int n = 0;
while (file.hasNext()) {
s = file.nextLine();
n++;
System.out.println(n + ". " + s);
//save your content here
b = b + "\n" + (n + ". " + s);
//end save your content
}// end while
PrintWriter printer = new PrintWriter(output);
printer.println(b);
printer.close();
}// end try
catch (FileNotFoundException fnfe) {
System.out.println("Was not able to locate testfile.txt.");
}
}// end m

Try this:
while(file.hasNextLine())
instead of:
while(file.hasNext())
and
b += (n+". "+s + "\n");
instead of:
b = (n+". "+s);

Change it to b += (n+". "+s);.

Related

Reading from a file, one word at a time by calling a method in Java

The goal is to write at least one other (static) method (function) for my main program to call. Perhaps a
method that processes a single line. Then the main program can call it repeatedly, as long as data is still
in the file. I am not able to create a function for my main program to call it. Maybe my thought process is not working at the moment would someone please help?
I've tried creating a method called readFile() as shown at the bottom, but i am receiving an error with using the scanner
public static void main(String[] args) {
//Scanner for user input
Scanner input = new Scanner(System.in);
//String variables for inputting the filename of the file and sending the text to the output.
String inputFileName;
System.out.print("Enter the filename with your student data:\n");
inputFileName = input.nextLine();
File fileInput = new File(inputFileName);
//final BufferedReader in = new BufferedReader(new FileReader(fileInput));
if(fileInput.exists()) {
System.out.print("File has been successfully opened.\n");
readFile();
}
else
{
System.out.print("Failed to open " + inputFileName + " file");
System.out.print("\nExiting Program...");
System.exit(0);
}
System.out.print("No more data.\nGoodbye!");
input.close();
}
public static void readFile() {
Scanner output;
try {
//I get an error on this line ----> output = new Scanner ();
while(output.hasNext()) {
System.out.print("Line 1 contains these tokens:\n");
String a = output.next();
String b = output.next();
String c = output.next();
String d = output.next();
String e = output.next();
System.out.print(a + "\n" + b + "\n" + c + "\n" + d + "\n" + e + "\n");
System.out.print("Line 2 contains these tokens:\n");
String f = output.next();
String g = output.next();
String h = output.next();
String i = output.next();
String j = output.next();
String k = output.next();
System.out.print(f +"\n" + g + "\n" + h + "\n" + i + "\n" + j + "\n" + k + "\n");
}
} catch (FileNotFoundException e1) {
System.out.print("Exception is caught here");
e1.printStackTrace();
}
}
}
the error i get with the Scanner:
Multiple markers at this line
- The constructor Scanner() is
undefined
- Resource leak: 'output' is never
You are validating your fileInput in main, and then ignoring that File and creating a new Scanner (incorrectly) in readFile. Instead construct a Scanner and pass it to fileInput. Like,
public static void readFile(Scanner output) {
// Scanner output
And pass a Scanner in (and use try-with-Resources to close it safely). Like
try (Scanner output = new Scanner(fileInput)) {
readFile(output);
}
Also consider reading an entire line and splitting on white-space
while (output.hasNextLine()) { // Use if to only read one line.
System.out.println("Line contains these tokens:");
System.out.println(Arrays.toString(output.nextLine().split("\\s+")));
}
(you currently have a lot of hardcoded token variables).

I need a program that will ask the user to enter the information to save, line to line in a file. How can I do it?

I need a program that will ask the user to enter the information to save, line to line in a file. How can I do it?
It has to look like this:
Please, choose an option:
1. Read a file
2. Write in a new file
2
File name? problema.txt
How many lines do you want to write? 2
Write line 1: Hey
Write line 2: How are you?
Done! The file problema.txt has been created and updated with the content given.
I have tried in various ways but I have not succeeded. First I have done it in a two-dimensional array but I can not jump to the next line.
Then I tried it with the ".newline" method without the array but it does not let me save more than one word.
Attempt 1
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
PrintStream escriptor = new PrintStream(f);
String [][] dades = new String [mida][3];
for (int i = 0; i < dades.length; i++) {
System.out.println("Write line " + i + " :");
for (int y=0; y < dades[i].length; y++) {
String paraula = sc.next();
System.out.println(paraula + " " + y);
dades[i][y] = paraula;
escriptor.print(" " + dades[i][y]);
}
escriptor.println();
}
Attempt 2
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
PrintStream escriptor = new PrintStream(f);
BufferedWriter ficheroSalida = new BufferedWriter(new FileWriter(new File(file1)));
for (int i = 0; i < mida; i++) {
System.out.println("Write line " + i + " :");
String paraula = sc.next();
ficheroSalida.write (paraula);
ficheroSalida.newLine();
ficheroSalida.flush();
}
System.out.println("Done! The file " + fitxer + " has been created and updated with the content given. ");
escriptor.close();
Attempt 1:
Write line 1: Hey How are
Write line 1: you...
Attempt 2:
Write line 1: Hey
Write line 2: How
Write line 3: are
Write line 4: you
Write line 5: ?
Well, you're almost there. First, I'd use a java.io.FileWriter in order to write the strings to a file.
It's not really necessary to use an array here if you just want to write the lines to a file.
You should also use the try-with-resources statement in order to create your writer. This makes sure that escriptor.close() gets called even if there is an error. You don't need to call .flush() in this case either because this will be done before the handles gets closed. It was good that you intended to do this on your own but in general its safer to use this special kind of statement whenever possible.
import java.io.*;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
File f = new File("/tmp/output.txt");
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
sc.nextLine(); // Consume next empty line
try (FileWriter escriptor = new FileWriter(f)) {
for (int i = 0; i < mida; i++) {
System.out.println(String.format("Write line %d:", i + 1));
String paraula = sc.nextLine();
escriptor.write(String.format("%s\n", paraula));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In cases where your text file is kind of small and usage of streamreaders/streamwriters is not required, you can read the text, add what you want and write it all over again. Check this example:
public class ReadWrite {
private static Scanner scanner;
public static void main(String[] args) throws FileNotFoundException, IOException {
scanner = new Scanner(System.in);
File desktop = new File(System.getProperty("user.home"), "Desktop");
System.out.println("Yo, which file would you like to edit from " + desktop.getAbsolutePath() + "?");
String fileName = scanner.next();
File textFile = new File(desktop, fileName);
if (!textFile.exists()) {
System.err.println("File " + textFile.getAbsolutePath() + " does not exist.");
System.exit(0);
}
String fileContent = readFileContent(textFile);
System.out.println("How many lines would you like to add?");
int lineNumber = scanner.nextInt();
for (int i = 1; i <= lineNumber; i++) {
System.out.println("Write line number #" + i + ":");
String line = scanner.next();
fileContent += line;
fileContent += System.lineSeparator();
}
//Write all the content again
try (PrintWriter out = new PrintWriter(textFile)) {
out.write(fileContent);
out.flush();
}
scanner.close();
}
private static String readFileContent(File f) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
return everything;
}
}
}
An execution of the example would be:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
4
Write line number #1:
Hello
Write line number #2:
Stack
Write line number #3:
Over
Write line number #4:
Flow
with the file containing after:
Hello
Stack
Over
Flow
And if you run again, with the following input:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
2
Write line number #1:
Hey
Write line number #2:
too
text file will contain:
Hello
Stack
Over
Flow
Hey
too
However, if you try to do it with huge files, your memory will not be enough, hence an OutOfMemoryError will be thrown. But for small files, it is ok.

How do I start a new line after a period, question mark, and exclamation point?

I am writing a program to change an input file. It should start a new line after a ? . and ! but I can't seem to figure it out. Each new line should also begin with an Uppercase letter which I think I got. It should also eliminate unnecessary spaces which I also believe I got.
For example: hello? bartender. can I have a drink!whiskey please.
Output should be:
Hello?
Bartender.
Can I have a drink!whiskey please.
It should only make a new line after those operators followed by a whitespace. If there is no space it will not make new line.
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String fileName, answer;
Scanner keyboard = new Scanner(System.in);
System.out.println("Test Input File:");
fileName = keyboard.nextLine();
File file = new File(fileName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(file);
}
catch(FileNotFoundException e)
{
System.out.println("Error opening file" + file);
System.exit(0);
}
System.out.println("Enter a line of text:");
String line = keyboard.nextLine();
outputStream.println(line);
outputStream.close();
System.out.println("This line was written to:" + " " + file);
System.out.println(" ");
TextFileProcessor.textFile();
}
}
Second Class
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Test Input File:");
String inputFile = keyboard.next();
System.out.print("Output File:");
String outputFile = keyboard.next();
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(inputFile));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(outputFile));
String line = inputStream.readLine();
line = line.replaceAll("\\s+", " ").trim();
line = line.substring(0,1).toUpperCase() + line.substring(1);
//This is where I would like to add code
while(line != null)
{
outputStream.println(line);
System.out.println(line);
line = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + inputFile + " not found");
}
catch(IOException e)
{
System.out.println("Error reading from file" + inputFile);
}
}
}
A simple regex would suffice:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
for(String s:"hello? bartender. can I have a drink!whiskey please.".replaceAll("(\\W)(\\s+)", "$1\n").split("\n"))
System.out.println(s.substring(0, 1).toUpperCase()+s.substring(1));
}
}
Output :
Hello?
Bartender.
Can I have a drink!whiskey please.
https://ideone.com/Zo2N7Q
Would this solve your problem?
if(line.endsWith("! ") || line.endsWith("? ") || line.endsWith(". ")) {
line = line + '\n';
}
You can use a "capture group" in a regex to achieve what you want.
line.replaceAll("(\\? )|(\\! )|(\\. )", "$0\n");
Update:
With regards to your comment on how to capitalize the first character of each line, you can use the toUpperCase method in the Character class.
line = Character.toUpperCase(line.charAt(0)) + line.substring(1);
Note:
If you are using Java 1.7 or above you should consider using a try-with-resources block for the Scanner
try (Scanner keyboard = new Scanner(System.in)) {
...
}
Then when you read input from the user you can manipulate it to the correct format before writing to your file. For example you could do something like...
System.out.println("Enter a line of text:");
String[] lines = keyboard.nextLine().replaceAll("(\\? )|(\\! )|(\\. )", "$0\n").split("\n");
// Replace the first character of each line with an uppercase character
for (int i = 0; i < lines.length; i++) {
lines[i] = Character.toUpperCase(lines[i].charAt(0)) + lines[i].substring(1);
}
Path path = Paths.get(fileName);
Files.write(path, Arrays.asList(lines), Charset.defaultCharset());
System.out.println("This line was written to:" + " " + path.toString());
System.out.println(" ");
As for reading and writing from files you are better off using the non-blocking Files class in the java.nio package. It's as simple as the following;
Path path = Paths.get(fileName);
Files.write(path, Arrays.asList(lines), Charset.defaultCharset());
Then for reading your file you can just use the readAllLines method.
List<String> lines = Files.readAllLines(path);
for (String line : lines ) {
System.out.println(line);
}

How to capitalize first letter in this program

I've written majority of this. I just can't figure out how to capitalize the first letter of each line. the problem is:
Write a program that checks a text file for several formatting and punctuation matters. The program asks for the names of both an input file and an output file. It then copies all the text from the input file to the output file, but with the following two changes (1) Any string of two or more blank characters is replaced by a single blank; (2) all sentences start with an uppercase letter. All sentences after the first one begin after either a period, a question mark, or an exclamation mark that is followed by one or more whitespace characters.
I've written most of the code. I just need help with the capitalization of the first letter of each sentence. Here's my code:
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
inputSent = inputStream.readLine();
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
//Find a way to make the first letter capitalized
while(inputSent != null)
{
outputStream.println(inputSent);
System.out.println(inputSent);
inputSent = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
}
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String inputName;
String result;
String sentence;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of your input file: ");
inputName = keyboard.nextLine();
File input = new File(inputName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(input);
}
catch(FileNotFoundException e)
{
System.out.println("There was an error opening the file. Goodbye!" + input);
System.exit(0);
}
System.out.println("Enter a line of text:");
sentence = keyboard.nextLine();
outputStream.println(sentence);
outputStream.close();
System.out.println("This line was written to:" + " " + input);
System.out.println("\n");
}
}
Since your code already contains inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1); I assume that inputSent can contain more than one sentence or might just represent a line of the file with parts of sentences.
Thus I'd suggest you first read the entire file into a string (if it's not too large) and then use split() on that string to break it into individual sentences, capitalize the first character and join them again.
Example:
String[] sentences = fileContent.split("(?<=[?!.])\\s*");
StringBuilder result = new StringBuilder();
for( String sentence : sentences) {
//append the first character as upper case
result.append( Character.toUpperCase( sentence.charAt(0) ) );
//add the rest of the sentence
result.append( sentence.substring(1) );
//add a newline
result.append("\n");
}
//I'd not replace the input, but to be consistent with your code
fileContent = result.toString();
The easiest way is maybe using WordUtil from Apache commons-langs.
You should use the capitalise method with the delimiters as parameter.
You can try the following regular expression:
(\S)([^.!?]*[.!?]( |$))
Code:
public static void main(String[] args) {
String inputSent = "hi! how are you? fine, thanks.";
inputSent = inputSent.replaceAll("\\s+", " ").trim();
Matcher m = Pattern.compile("(\\S)([^.!?]*[.!?]( |$))").matcher(inputSent);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase() + m.group(2) + "\n");
}
m.appendTail(sb);
System.out.println(sb);
}
See a demo online.
Output:
Hi!
How are you?
Fine, thanks.
In the ASCII table lower and upper case are just integers that are 32 positions away from each other...
try something like this:
String inputSent = .... //where ever it does come from...
System.out.println(inputSent.replace(inputSent.charAt(0), (char) (inputSent.charAt(0) - 32)));
or use some kind of APACHE libs like WordUtils.
I would change the textFile() to the below:
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
while ((inputSent = inputStream.readLine()) != null) {
char[] chars = inputSent.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
inputSent = new String(chars);
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
System.out.println("-> " + inputSent);
outputStream.println(inputSent);
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
This will read the text file line by line.
Upper the first char
Do this in a while loop
The problem with your original textFile() is that it only applies uppercase first char, blank space etc on the very first line it reads.

Text analysis Word Counter Java

I need to write code that reads and does a text analysis of a file. One of the things it needs to do is to count how many words there are in the file. I wrote a method countWords, but when I run the program it returns 0. The text file I am using contains the following:
Ask not what your country can do for you
ask what you can do for your country
So it clearly should return 17 and not 0. What did I do wrong?
public class TextAnalysis {
public static void main (String [] args) throws IOException {
File in01 = new File("a5_testfiles/in01.txt");
Scanner fileScanner = new Scanner(in01);
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
System.out.println("Number of words in file wordlist: " );
countWords(fileScanner);
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static void countWords (Scanner s) throws IOException {
int count = 0;
while(s.hasNext()) {
String word = s.next();
count++;
}
System.out.println(count);
}
try this?
void countWords()
{
String temp;
File path = new File("c:/Bala/");//give ur path
File file = new File(path, "Bala.txt");//give ur filename
FileReader fr = new FileReader(file);
char cbuf[] = new char[(int) file.length()];
fr.read(cbuf);
temp = new String(cbuf);
String count[]=test.split("\\s");
System.out.println("Count:"+t.length);
}
You already read the scanner and reading it again. just create another scanner to use in count words method
fileScanner = new Scanner(<your file object>);
before
countWords(fileScanner);
Hope this helps.
Declare a new scanner for your count words method, the problem lies under s.next(); it reads the next word in your buffer and discard the previous ones, so after you called your longest word method, the scanner buffer has been used up.

Categories