Adding printlines and text to FileWriter (writer.write) - java

I was wondering how to add print lines to a filewriter output.
At the moment when the full code has run and I open the .txt folder it looks like this
https://gyazo.com/b287d61eafb100dce1ce2476b71623e9
I was wondering how I could add text and printlines to make the format similar to this : https://i.gyazo.com/def6e157e24dc0ed0fe68e1509152405.png
try
{
FileWriter writer = new FileWriter("Gamer Report Data.txt");
writer.write(gamerName);
writer.write(System.getProperty( "line.separator"));
writer.write(gamerReport);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}

Like this:
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
//This line will split the gameReport string by the ':' separator
//Into an array of strings.
string[] report = gameReport.split(":");
//Edit here with regards to latest comment
//This will print the game score if the reports array has data.
if(report == null) {
writer.println("Game report was null.");
} else if(report.length == 3) {
writer.println("Game:" + report[0]+", score=" + report[1] +", minutes played="+ report[2]);
}
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}

Is it what you want? just similar to second picture.
import java.io.FileWriter;
import java.io.IOException;
//if your java file name is ABC.java then your class name is ABC
public class ABC
{
public static void main(String[] args) throws IOException
{
String text = "Name here";
String text2 = "Data here";
FileWriter fw = new FileWriter("Output.txt");
fw.write(text);
fw.write(System.lineSeparator());
if(text.length()>text2.length())
for(int i=0;i<text.length();i++) fw.write("-");
else
for(int i=0;i<text2.length();i++) fw.write("-");
fw.write(System.lineSeparator());
fw.write(text2);
fw.close();
}
}

Related

Expanding abbreviations from .csv file

So I have this task to do, I need to expand text abbreviations from the message into their full form from the .csv file, I loaded that file into HashMap, with keys as abbreviations and values as full forms. There is a loop to iterate through the keys and if statement which replaces abbreviation to full form if it finds any. I kind of figured it out and it is working as it should but I want to send this changed String (with abbreviations expanded) somewhere else out of if statement to save the full message to the file. I know that this String exists only in this if statement but maybe there is another way of doing it? Or maybe I'm doing something wrong? I became a bit rusty with Java so maybe there is a simple explanation that I don't know about. Here is the code I have :
public class AbbreviationExpander {
static void AbrExpander(String messageBody) {
//read the .csv file
String csvFile = "textwords.csv";
String line = "";
String cvsSplitBy = ",";
String bodyOut = messageBody;
HashMap<String, String> list = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] abbreviatonFile = line.split(cvsSplitBy);
//load the read data into the hashmap
list.put(abbreviatonFile[0], abbreviatonFile[1]);
}
for (String key : list.keySet()) {
//if any abbreviations found then replace them with expanded version
if (messageBody.contains(key)) {
bodyOut = bodyOut.replace(key, key + "<" + list.get(key).toLowerCase() + ">");
try {
File file = new File("SMS message" + System.currentTimeMillis() + ".txt");
FileWriter myWriter = new FileWriter(file);
myWriter.write(bodyOut);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
} catch (IOException f) {
f.printStackTrace();
}
}
}
Not sure I understood well your problem. But I think you should separate the different steps in your code.
I mean your try-catch block that writes your output should be outside the for-loop and outside the reading try-catch. And your for-loop should be outside your reading try-catch.
public class AbbreviationExpander {
static void AbrExpander(String messageBody) {
String csvFile = "textwords.csv";
String line = "";
String cvsSplitBy = ",";
String bodyOut = messageBody;
HashMap<String, String> list = new HashMap<>();
//read the .csv file
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] abbreviatonFile = line.split(cvsSplitBy);
//load the read data into the hashmap
list.put(abbreviatonFile[0], abbreviatonFile[1]);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
//if any abbreviations found then replace them with expanded version
for (String key : list.keySet()) {
if (messageBody.contains(key)) {
bodyOut = bodyOut.replace(key, key + "<" + list.get(key).toLowerCase() + ">");
}
}
//output the result in your file
try {
File file = new File("SMS message" + System.currentTimeMillis() + ".txt");
FileWriter myWriter = new FileWriter(file);
myWriter.write(bodyOut);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

how can I add new lines in txt using java, and without empty spaces

When I am writing text in this txt file, there either is no space between the new string and the old existing string, or there is extra lines, which messes up my other algorithms.
public String writeStudent(String file, String name)
{
String txt = "";
//set through put method
try(FileWriter fw = new FileWriter(file + ".txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(name + "\r\n");
//save userinput into class1.txt
txt ="added: " + name;
}
catch(IOException e)
{
System.out.println("error");
e.printStackTrace();
// detact error
}
return txt;
}
This is the code I am using to writing in txt, using (name + "\r\n") gives me extra empty lines.
How about use BufferedWriter instead of PrintWriter?
It's my sample code. please try test below code.
import java.io.*;
public class Stackoverflow {
public static void main(String[] args) {
File file = new File("C:\\test.txt");
OutputStream outputStream = null;
Writer writer = null;
BufferedWriter bufferedWriter = null;
try {
outputStream = new FileOutputStream(file);
writer = new OutputStreamWriter(outputStream);
bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write("Hello");
bufferedWriter.write("\r\n");
bufferedWriter.write("\r\n");
bufferedWriter.write("Bye");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (Exception ignore) {
}
}
if (writer != null) {
try {
writer.close();
} catch (Exception ignore) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception ignore) {
}
}
}
}
}
output
Hello
Bye
The problem is the println function automatically adds new line at end of input string.
out.println(name + "\r\n"); Is effectively the same as out.print(name + "\r\n\r\n");
Lastly you need to think about if new line needs to be before or after your student name.
The solution is to simply use print instead of println and add a new line before the student name
For example.
Given existing text file
John Doe
and you want a new name to be added as
John Doe
Jane Doe
The newline is actually before your name input. Meaning you should use something like out.print("\r\n" + name);

Need help loading in a file that contains Strings and a Collection<String>?

I have two methods, one for writing information a textfile and one for reading in that same text file. I have the writing method working which writes various String objects and a Collection to the file. The problem comes when loading or reading the same file? I don't quite know how to read in the Collection of notes from the file? Here are both my methods.
public void writeDvd() throws DVDLibraryException {
PrintWriter out;
try {
out = new PrintWriter(new FileWriter(LIBRARY));
} catch (IOException ex) {
throw new DVDLibraryException("Problem writing to file", ex);
}
List<DVD> dvdList = this.returnListDvds();
for (DVD currentDvd : dvdList) {
out.print(currentDvd.getTitle() + DELIMETER
+ currentDvd.getReleaseDate() + DELIMETER
+ currentDvd.getRating() + DELIMETER
+ currentDvd.getDirectorsName() + DELIMETER
+ currentDvd.getStudio() + DELIMETER
+ currentDvd.getNotes());
out.flush();
}
out.close();
}
And here is my loadDVD() method:
public void loadDvd() throws DVDLibraryException {
Scanner sc;
try {
sc = new Scanner(new BufferedReader(new FileReader(LIBRARY)));
} catch (FileNotFoundException ex) {
throw new DVDLibraryException("Could not read file", ex);
}
String currentLine;
String[] currentTokens;
while (sc.hasNext()) {
currentLine = sc.nextLine();
currentTokens = currentLine.split(DELIMETER);
DVD currentDvd = new DVD(currentTokens[0], currentTokens[1],
currentTokens[2], currentTokens[3], currentTokens[4]);
//I'm trying to do above with the currentTokens[5] for the Collection of Strings but not sure how to approach the problem?
//This does not work
//Collection<String> notes = currentDvd.getValuesNotes();
//currentDvd.setValuesOfNotesForReading(notes);
//String s = String.join(DELIMETER, notes);
//currentDvd.setValuesOfNotesForReading(s);
dvds.put(currentDvd.getTitle(), currentDvd);
}
sc.close();
}
Assuming DELIMITER is not a newline and your intent is to write all the fields in one row, you seem to be missing an out.println() after the out.print().

Java PrintWriter doesn't append to existing .txt file after closing

I've run into some problems trying to append to an existing text file.
It doesn't seem to append a line text. So far i've got this method:
public static void addLine(File f, String line) {
try {
FileWriter fw = new FileWriter(f.getName(), true);
BufferedWriter buffer = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(buffer);
pw.println(line);
pw.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
and in my main i've got the following:
public static void main(String[] args) {
File f = new File("adresOfFile");
if (f.exists() && !f.isDirectory()) {
System.out.println("File " + f.getName() + " exists!");
System.out.println("\n" + "Path: " + f.getAbsolutePath());
System.out.println("\n" + "Parent: " + f.getParent());
System.out.println("\n" + "--------------CONTENT OF FILE-------------");
addLine(f, "");
addLine(f, "The line to append");
try {
displayContent(f);
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("File not found");
}
}
When I run the program it doesn't seem to give any errors. Running the program should print out the existing text (displayContent), which is done after appending (addLine). But when I run it, it only shows the existing text, without the appended line.
It doesn't show up in the text file either. I tried to put a System.out.println(); in the method, and it prints, so I know its running the method properly, just not appending.
EDIT AWNSER: replaced f.getName() with f, and added pw.flush before pw.close()
I think that your displayContent(File) function has bugs.
The above code does append to the file.
Have a look at the file to see if anything is appended.
Also do you need to create PrintWriter object each time you append a line?
If there are many continuous lines to be appended, try using a single PrintWriter/ BufferedWriter object by creating a static/final object.

Using java.io.package / How to read data from a variable and store it in a file?

could someone please provide a hint how i can go about reading data from a variable (some string file) which holds my random computations and store the output in a text file and probably some functionality for working with it.
thanks,
steliyan
I have 2 examples for you; the first is reading from a text file, the second is writing to one.
import java.io.*;
class FileRead {
public static void main(String args[]) {
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
br.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.*;
class FileWrite {
public static void main(String args[]) {
String var = "var";
try {
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(var);
//Close the output stream
out.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

Categories

Resources