Add a paragraph in File - java

I would like to write a paragraph using file.
This is my code(my effort).
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
try {
BufferedWriter out = new BufferedWriter(new FileWriter("C:/Users/Akram/Documents/akram.txt")) ;
System.out.println("Write the Text in the File ");
String str = input.nextLine();
out.write(str);
out.close();
System.out.println("File created successfuly");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With this code I can add just one word but I want to add a lot of word (paragraph).

I would use a while loop around Scanner#hasNextLine(). I would also recommend a PrintWriter. So, all together, that would look something like,
Scanner input = new Scanner(System.in);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(
"C:/Users/Akram/Documents/akram.txt"));
System.out.println("Write the Text in the File ");
while (input.hasNextLine()) {
String str = input.nextLine();
out.println(str);
}
System.out.println("File created successfuly");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}

In order to write a paragraph, Decide a terminating character or string,Write your code so that it takes the input till that character or string is given in the input, Do some operation to remove the character in the file,
The code which I used is given below,Terminating Character is +
I haven't kept try and catch statements to reduce complexity in understanding
pw = new PrintWriter(new FileWriter("E://files//myfile.txt"));
System.out.println("Write the Text in the File,End the text with + ");
do
{
Scanner sc =new Scanner(System.in);
String S=sc.nextLine();
if(S.endsWith("+"))
{
S= S.replace("+"," ");
flag=1;
pw.println(S);
}
else
pw.println(S);
}while(flag!=1);
Cheers

Related

Java (Read and write to file)

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class backup {
public static void main(String[] args) {
System.out.println("\nThe names in the file are:\n");
readFromFile();
}
public static void readFromFile() {
try {
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt");
Scanner input = new Scanner(System.in);
while (file.hasNext()) {
String name = file.nextLine();
System.out.printf("Please enter " + name + "'s mark:");
int mark = input.nextInt();
Scanner kybd = new Scanner(System.in);
{
if (mark >= 40) {
// System.out.println(name + " has passed");
pass.println(name);
} else {
// System.out.println(name + " has failed");
fail.println(name);
}
}
} // end while
} // end try
catch (IOException ioe) {
System.out.println("Error handling file");
} // end catch
}// readFromFile
}
Unable to write to the file pass and fail the Names file is just a list of names if the user scores over 40 they go into the pass however i cant get the txt file to populate the output.
When i insert my printwriter in the while it is only the last entry which gets added to either pass or fail txt file.
The PrintWriter only really writes when they are closed (close) or flushed (flush or maybe when it thinks it is time ;-)).
Try to use try-with-resources whenever possible, that way you do not need to think about closing/flushing a stream or writer. try-with-resources takes care that AutoClosable-implementations are closed automatically at the end of the try-block.
Your sample rewritten with try-with-resources (only showing the initial part):
try(
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt")
) {
The rest can stay as is... or if you like: you may also want to lookup the Files-API. Maybe using Files.lines is something for you?
You should call the function close on your file for it to be written on the dsisk.
Otherwise you modifications are only in memory
Something like: file.close()
If you use PrintWriter, you have to close the stream at the end. Otherwise, it will be only in memory. Try this:
try {
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt");
Scanner input = new Scanner(System.in);
while (file.hasNext()) {
String name = file.nextLine();
System.out.printf("Please enter " + name + "'s mark:");
int mark = input.nextInt();
//Scanner kybd = new Scanner(System.in);
//{
if (mark >= 40) {
// System.out.println(name + " has passed");
pass.println(name);
} else {
// System.out.println(name + " has failed");
fail.println(name);
}
//}
} // end while
pass.close();
fail.close();
} // end try
catch (IOException ioe) {
System.out.println("Error handling file");
}
You need to make sure that you add a finally block at the end and call the close method on anything that is closeable so in this case on the printwriter. In this case
pass.close() and fail.close().

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);
}

Skipping whitespace on new line?

I can't seem to get this correct. Basically if the line is blank inside the text file it should skip the line instead of numbering it.
Ex: If the file contains, Apples,Oranges,Pineapples
it should produce
Apples
Oranges
Pineapples
or
1. Apples
(blank)
Oranges
Pineapples
try {
Scanner reader = new Scanner(System.in);
System.out.print("Enter file name with extension: ");
File file = new File(reader.nextLine());
reader = new Scanner(file);
int counter = 1;
while (reader.hasNextLine())
{
if (reader.equals(" ")){
System.out.println();
}else{
String line = reader.nextLine();
System.out.printf("%2d.", counter++); // Use printf to format
System.out.println(line);
}
}
reader.close();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
Space or " " is actually totally different to an empty line...
so the reason why is not working is the condition
if (reader.equals(" ")){.....
use instead the String.isEmpty() method, since this is what you need...
or try this:
...
reader = new Scanner(file);
int counter = 1;
while (reader.hasNextLine()) {
final String line = reader.nextLine();
if (line.isEmpty()) {
System.out.println("This is an empty line");
} else {
System.out.printf("%2d.", counter++); // Use printf to format
System.out.println(line);
}
}
reader.close();
...

Java Login Codes Reading multiple lines from file not working

I got this code below to do a simple password (hashed) check function. But I encountered a problem, the code seem to work only for single line data in the file, the check works for Line1 but not Line2, I am unsure what is wrong. The data is shown below
the result is supposed to be hashedP matching either Line1 or 2. But it end up matching Line1 only
260670134225f2a24b59121739fec73584b0ddb6b49c39e31bd1df5483ac144d //Line1
cf80cd8aed482d5d1527d7dc72fceff84e6326592848447d2dc0b0e87dfc9a90 //Line2
Code:
public static void LoginMenu() {
System.out.println("Please Enter Your Password: ");
Scanner UserPass = new Scanner(System.in);
String UserP = UserPass.nextLine();
String hashedP = Utility.getHash(UserP);
File file = new File("admin.dat");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String fileline = scanner.nextLine();
if (!(fileline.equals(hashedP))) {
System.out.println("Login Failed!");
LoginMenu();
}
else {
System.out.println("Login Successful.\n");
AdminMenu();
}
}
scanner.close();
}
catch (FileNotFoundException exc) {
exc.printStackTrace();
}
}
Let's analyse this section:
while (scanner.hasNextLine()) {
String fileline = scanner.nextLine();
if (!(fileline.equals(hashedP))) {
System.out.println("Login Failed!");
LoginMenu();
}
else {
System.out.println("Login Successful.\n");
AdminMenu();
}
}
We enter the while loop.
We read the first line from the file.
We check it against hashedP.
3.1. If it matches, we display the admin screen.
3.2. If it does not match, we prompt the user to log in again.
You never even reach the second line in the file, it fails too fast.
You should refactor your loop to try harder:
boolean failed = true;
while (scanner.hasNextLine())
{
String fileline = scanner.nextLine();
if (fileline.equals(hashedP))
{
failed = false;
System.out.println("Login Successful.\n");
AdminMenu();
}
}
if(failed)
{
System.out.println("Login Failed!");
LoginMenu();
}
Unrelated to that, it's never a good idea to call a function recursively if in any way avoidable.
In this case, for example, admin.dat and a new stdin Scanner will be opened as many times as an incorrect password is entered, which is poorly designed.
I suggest using a while(true) loop instead to read the password and doing everything else before that:
public static void LoginMenu()
{
ArrayList<String> hashes = new ArrayList<String>();
File file = new File("admin.dat");
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
hashes.add(scanner.nextLine());
}
scanner.close();
}
catch (FileNotFoundException exc)
{
exc.printStackTrace();
return;
}
Scanner UserPass = new Scanner(System.in);
while (true)
{
System.out.println("Please Enter Your Password: ");
String UserP = UserPass.nextLine();
String hashedP = Utility.getHash(UserP);
if (hashes.contains(hashedP))
{
System.out.println("Login Successful.\n");
AdminMenu();
break;
}
System.out.println("Login Failed!");
}
}

Counting a specific character in a file with Scanner

I'm trying to write a program that prompts the user to enter a character, and count the number of instances said character appears in a given file. And display the number of times the character appears.
I'm really at a loss, and I'm sorry I don't have much code yet, just don't know where to go from here.
import java.util.Scanner;
import java.io.*;
public class CharCount {
public static void main(String[] args) throws IOException {
int count = 0;
char character;
File file = new File("Characters.txt");
Scanner inputFile = new Scanner(file);
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a single character");
character = keyboard.nextLine().charAt(0);
}
}
You need the below code to read from the file and check it with the character you've entered. count will contain the occurrences of the specified character.
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) !=null) {
for(int i=0; i<line.length();i++){
if(line.charAt(i) == character){
count++;
}
}
}
} catch (FileNotFoundException e) {
// File not found
} catch (IOException e) {
// Couldn't read the file
}

Categories