Write problem - lossing the original data - java

Every time I write to the text file I will lose the original data, how can I read the file and enter the data in the empty line or the next line which is empty?
public void writeToFile()
{
try
{
output = new Formatter(myFile);
}
catch(SecurityException securityException)
{
System.err.println("Error creating file");
System.exit(1);
}
catch(FileNotFoundException fileNotFoundException)
{
System.err.println("Error creating file");
System.exit(1);
}
Scanner scanner = new Scanner (System.in);
String number = "";
String name = "";
System.out.println("Please enter number:");
number = scanner.next();
System.out.println("Please enter name:");
name = scanner.next();
output.format("%s,%s \r\n", number, name);
output.close();
}

You must open the file for append.

You need to open myFile in append mode. See this link for an example.

As others have said, use the append option.
This code can write data in the default platform encoding:
private static void appendToFile() throws IOException {
boolean append = true;
OutputStream out = new FileOutputStream("TextAppend.txt", append);
Closeable resource = out;
try {
PrintWriter pw = new PrintWriter(out);
resource = pw;
pw.format("%s,%s %n", "foo", "bar");
} finally {
resource.close();
}
}
There are a number of classes you can wrap around an OutputStream to achieve the same effect. Be aware that the above approach can lose data when the code is run on a platform that doesn't use a Unicode default encoding (like Windows) and may produce different output on different PCs.
One case in which care is need is if the encoding inserts a byte order mark. If you wanted to write lossless Unicode text in UTF-16 marked with a little-endian BOM, you would need to check the file for existing data.
private static void appendUtf16ToFile() throws IOException {
File file = new File("TextAppend_utf16le.txt");
String encoding = (file.isFile() && file.length() > 0) ?
"UnicodeLittleUnmarked" : "UnicodeLittle";
boolean append = true;
OutputStream out = new FileOutputStream(file, append);
Closeable resource = out;
try {
Writer writer = new OutputStreamWriter(out, encoding);
resource = writer;
PrintWriter pw = new PrintWriter(writer);
resource = pw;
pw.format("%s,%s %n", "foo", "bar");
} finally {
resource.close();
}
}
Supported encodings:
Java 6
Java 5

We're you've got: new Formatter(myFile); you'll want to use new Formatter(new FileWriter(myfile, true). The true indicates you want to append to that file.

Related

check if the word in the set equals word in outside file

I have a set of words and an outside file.
I want to check if a word in the set is already present in the outside file. If the word is already in the file, then do nothing, if the word is not in the outside file already, then add it to the outside file.
This is the code I have written:
public static void toFile(Set<String> vocab, String filename)
{
try
{
for(String vocabWord : vocab)
{
File file = new File(filename);
Scanner sc2 = new Scanner(file);
while(sc2.hasNextLine())
{
String docWord = sc2.nextLine();
if (!(vocabWord.equals(docWord)))
{
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
else
break;
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
I am using three different text documents to test it, have the line "test file one", "test file two", and "test file three".
The output I was expecting was: "test file three" (it is connected with a stop list which one and two are part of, and has been working)
However, when I run it, either with only one of the files or all three consecutively, the file always comes out empty.
I tried changing up things in the method, but nothing has worked, I either get an infinite loop or nothing in the outside file.
I am not sure what I am missing... I would really appreciate any help.
I tried this and added some comments for explanation. I have tested on local machine and it works
public static void toFile(Set<String> vocab, String filename) {
try {
for(String vocabWord : vocab) {
//task for each String in our Set
File file = new File(filename);
Scanner sc2 = new Scanner(file);
boolean exists = false;//lets say it doesn't exist
while(sc2.hasNextLine()) {
//task for each line in the text
//search the whole file first for the word
String docWord = sc2.nextLine();
if (docWord.equals(vocabWord)){
exists = true;
break;
}
}
if (!exists) {
//add the vocabWord only if it doesnt exists
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
To append the missing vocabulary in order of vocab, you can reduce the file operations
as such:
public static void toFile(Set<String> vocab, String filename) {
try {
Charset charset = Charset.defaultCharset();
Path path = Paths.get(filename);
Set<String> existing = Files.lines(path, charset)
.collect(Collectors.toSet());
if (!existing.isEmpty()) {
try (BufferedWriter bw = Files.newBufferedWriter(path, charset,
StandardOpenOption.APPEND);
PrintWriter printWriter = new PrintWriter(bw)) {
vocab.stream()
.filter(word -> !existing.contains(word))
.forEach(word -> printWriter.println(word));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

Issues writing doubles to files, writing nothing

I seem to be missing something when it comes to writing doubles to text files, when I check the file, just blank space is present. When I read from the file and print with System.out.println(); it just prints nothing... What's going wrong here? Do I need to do some converting?
import java.io.*;
import javax.swing.JOptionPane;
public class ReadCalcAveragePrint {
double firstNum;
double secondNum;
double average;
public void readFile() {
try {
File f = new File("numbers.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String one = br.readLine();
String two = br.readLine();
firstNum = Double.parseDouble(one);
secondNum = Double.parseDouble(two);
average = (firstNum + secondNum) / 2;
JOptionPane.showMessageDialog(null, average, "title", JOptionPane.PLAIN_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
public void writeFile() {
try {
File f = new File("result.txt");
FileOutputStream fos = new FileOutputStream(f);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeDouble(average);
dos.flush();
fos.close();
System.out.println("Printed.");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
public void readResult() {
try {
File f = new File("result.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String one = br.readLine();
System.out.println(one);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
public static void main(String[] args) {
new ReadCalcAveragePrint().readFile();
new ReadCalcAveragePrint().writeFile();
new ReadCalcAveragePrint().readResult();
}
}
In the main you are creating 3 different objects, only the first is going to contain the numbers you read from the file.
You should just create and reuse one object:
public static void main(String[] args) {
ReadCalcAveragePrint obj = new ReadCalcAveragePrint();
obj.readFile();
obj.writeFile();
obj.readResult();
}
Also you are writing the result file using DataOutputStream which is meant to write the data in binary form. If you just want to save the result as text you should use FileWriter instead:
File f = new File("result.txt");
FileWriter fw = new FileWriter(f);
fw.write(String.valueOf(average));
fw.close();
see the javadoc of writeDouble:
Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.
you write 8 bytes that may not be assigned to any alphanumeric character. Then you read it a line as a String (characters up to the next 'new line' char).
In this case, the 'new line' char can be anywhere, or nowhere (depending on the result).
8 bytes in file means almost 4 chars, very likely, no one is a "visible character".
Try to read a byte[8] from the InputStream (not from a Buffered one), and then put those 8 bytes into DoubleBuffer, then you can get the double value represented by those bytes and writen to the file before.

set encoding as UTF-8 for a FileWriter [duplicate]

This question already has answers here:
Write a file in UTF-8 using FileWriter (Java)?
(9 answers)
Closed 5 years ago.
Below is my code, it is intended to take two .ckl files, compare the two, add the new items and create a new merged file. The program executes correctly when run in Netbeans however, when executing the .jar the program doesn't appear to be encoding the file in UTF-8. I am rather new to programming and would like to know where or how I might need to be enforcing this encoding to take place?
** I have removed the Swing code and other lines so that only my method is shown, the method that does all of the comparing and merging.
public void mergeFiles(File[] files, File mergedFile) {
ArrayList<String> list = new ArrayList<String>();
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, false);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
// Going in a different direction. We are using a couple booleans to tell us when we want to copy or not. So at the beginning since we start
// with our source file we set copy to true, we want to copy everything and insert vuln names into our list as we go. After that first file
// we set the boolean to false so that we dont start copying anything from the second file until it is a vuln. We set to true when we see vuln
// and set it to false if we already have that in our list.
// We have a tmpCopy to store away the value of copy when we see a vuln, and reset it to that value when we see an </VULN>
Boolean copy = true;
Boolean tmpCopy = true;
for (File f : files) {
textArea1.append("merging files into: " + mergedFilePathway + "\n");
FileInputStream fis;
try {
fis = new FileInputStream(f);
// BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(mergedFile), "UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
// Skip the close checklist and we can write it in at the end
if (aLine.trim().equals("</iSTIG>")) {
continue;
}
if (aLine.trim().equals("</STIGS>")) {
continue;
}
if (aLine.trim().equals("</CHECKLIST>")) {
continue;
}
if (aLine.trim().equals("<VULN>")) {
// Store our current value of copy
tmpCopy = copy;
copy = true;
String aLine2 = in.readLine();
String aLine3 = in.readLine();
String nameLine = in.readLine();
if (list.contains(nameLine.trim())) {
textArea1.append("Skipping: " + nameLine + "\n");
copy = false;
while (!(aLine.trim().equals("</VULN>"))) {
aLine = in.readLine();
}
continue; // this would skip the writing out to file part
} else {
list.add(nameLine.trim());
textArea1.append("::: List is now :::");
textArea1.append(list.toString() + "\n");
}
if (copy) {
out.write(aLine);
out.newLine();
out.write(aLine2);
out.newLine();
out.write(aLine3);
out.newLine();
out.write(nameLine);
out.newLine();
}
} else if (copy) {
out.write(aLine);
out.newLine();
}
// after we have written to file, if the line was a close vuln, switch copy back to original value
if (aLine.trim().equals("</VULN>")) {
copy = tmpCopy;
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
copy = false;
}
// Now lets add the close checklist tag we omitted before
try {
out.write("</iSTIG>");
out.write("</STIGS>");
out.write("</CHECKLIST>");
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Java has extensive, highly informative documentation. Keep it bookmarked. Refer to it first, whenever you have difficulty. You'll find it's frequently helpful.
In this case, the documentation for FileWriter says:
The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
If you want to be sure your file will be written as UTF-8, replace this:
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, false);
with this:
Writer fstream = null;
BufferedWriter out = null;
try {
fstream = new OutputStreamWriter(new FileOutputStream(mergedFile), StandardCharsets.UTF_8);
For those, who use FileWriter in order to append to an existing file, the following will work
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8)) {
//code
}
You can just run it with the command java -Dfile.encoding=UTF-8 -jar yourjar.jar.
Follow this for more info.

how to take the output from command prompt and make a text file out of it using language Java

This is what I have found, but in this code it reads line on what you put in, and I don't want that
I am doing a program called Knight's Tour, and I getting output in Command prompt. All I want to do is to read the lines from Command prompt and store it an output file called knight.txt. Can anyone help me out. Thanks.
try
{
//create a buffered reader that connects to the console, we use it so we can read lines
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in.readLine();
//create an print writer for writing to a file
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//output to the file a line
out.println(lineFromInput);
//close the file (VERY IMPORTANT!)
out.close();
}
catch(IOException e)
{
System.out.println("Error during reading/writing");
}
You don't need Java for that. Just redirect the output of the game to a file:
game > knight.txt
You may look at this example, it shows how write data into an file, if the file exist it show how to append to the file,
public class FileUtil {
public void writeLinesToFile(String filename,
String[] linesToWrite,
boolean appendToFile) {
PrintWriter pw = null;
try {
if (appendToFile) {
//If the file already exists, start writing at the end of it.
pw = new PrintWriter(new FileWriter(filename, true));
}
else {
pw = new PrintWriter(new FileWriter(filename));
//this is equal to:
//pw = new PrintWriter(new FileWriter(filename, false));
}
for (int i = 0; i < linesToWrite.length; i++) {
pw.println(linesToWrite[i]);
}
pw.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
//Close the PrintWriter
if (pw != null)
pw.close();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.writeLinesToFile("myfile.txt", new String[] {"Line 1",
"Line 2",
"Line 3"}, true);
}
}
In the code you posted, just change lineFromInput to whatever string you want to output to the text file.
I guess what you are doing is writing the output to file using file operations in java but what you want can be done in an easier way as follows -
No code is required for this. The output can be redirected by
file > outputfile
This is independent of java.

Reading and displaying data from a .txt file

How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

Categories

Resources