Alright so to get straight to the point I've coded a simple application in which it gets the string of the first line of the files it goes through and then I make it to log all the strings it gets to a txt file but when it logs it just continues to replace itself with the new strings in the other files.
I want it to log the strings it gets then write the new string from the other file in a new line but I cannot seem to make it work.
To anyone who can help me fix this I'd really appreciate it.
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
writer.write(line1);
writer.newLine();
writer.close();
}
}
}
Note :
you must open and close the writer object, outside of for loop
Try this
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
writer.write(line1);
writer.newLine();
}
writer.close();
}
}
You are reopening the file logged.txt in each iteration of your text loop. This will truncate the file and start writing at the beginning again. If you really want to reopen the file, you need to use append mode: FileWriter("filename.txt", true), but you probably want to open the BufferedWriter before your loop and close it afterwards.
You new your writer every time. Add the new line before the for begins.
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
writer.write(line1);
writer.newLine();
}
writer.close();
}
}
Related
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();
}
}
I've spent over an hour on this, and i just can't get any text to show up in the .txt file. What am i doing wrong?
import java.util.*;
import java.io.*;
public class writer {
public static void main(String[] args) {
try {
File txt = new File("myTextFile.txt");
FileWriter fw = null;
fw = new FileWriter(txt);
BufferedWriter edit = null;
edit = new BufferedWriter(fw);
String s = "more text", line = null;
edit.write(s);
Scanner sc = new Scanner(txt);
while (sc.hasNextLine()) {
String i = sc.nextLine();
System.out.println(i);
}
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Edit: Added a .write, but it's still not working
You never close the BufferedWriter instance and you never flush it either. So you never leave a change the buffer of the stream to be effectively written in the physical file.
Actually you read the file from the same source that you use just before to write in. So you have to explicitly flush the buffer of BufferedWriter before reading the content with the Scanner :
BufferedWriter edit = new BufferedWriter(fw);
String s = "more text", line = null;
edit.write(s);
edit.flush(); // modification here
Scanner sc = new Scanner(txt);
I've been working on a small project in Java. The program writes to a log file from different methods . But each time a method is used , the content of the file gets deleted and all what's written in it is the result of the last method.
here's a code snippet of the program :
// dir , log_file , exp_date and amount are declared in the code removed
public static void WriteHeader() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Console console = System.console();
exp_date = console.readLine("Enter a string here: ");
bufferedWriter.write(exp_date);
bufferedWriter.close();
}
public static void WriteNewLine() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter2 = new BufferedWriter(fileWriter);
Console console = System.console();
amount = console.readLine("Enter another string here :");
bufferedWriter2.newLine();
bufferedWriter2.write(amount);
bufferedWriter2.close();
}
You need to create the writer in append mode http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
You need to open file in append mode otherwise once you close the file and reopen it to write, it would erase previous data. http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String, boolean)
FileWriter fileWriter = new FileWriter(dir+"/"+log_file, true);
FileWriter fw = new FileWriter(file, true);
I am pretty sure FileWriter has an overloaded constructor for appending to a file instead of overwriting a file
I would also check if the file exists first.
file.exists();
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.
i trying to save this string with a file list into a file but it only saves the last one.. what is the problem here? :(
public void fileprinter() throws IOException{
File dir = new File("c:");
String[] children = dir.list();
if (children == null) {
} else {
for (int i=0; i<children.length; i++) {
String filename = new StringBuffer().append(children[i]).toString();
System.out.println(filename);
Writer output;
File file = new File("D:/file.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(filename);
output.close();
}
}
}
You keep overwriting the same file in the loop, so only the last line will "survive".
Open the BufferedWriter outside of the loop (once!) and close it when done.
An alternative would be to open in append mode, but even then don't reopen the same file in a loop over and over again.