Search for a file and append to it - java

I have a program where it searches for a file(it already has some content in it) based on the given directory path and lets the user add more content to that file. I was able to show all the files on the directory, but I am not sure how to select a file and write more content to it. Here is my code so far:
public static void main(String [] args)
{
// This shows all the files on the directory path
File dir = new File("/Users/NasimAhmed/Desktop/");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
// write content to sample.txt that is in the directory
out(dir, "sample.txt");
}
}
}
public static void out(File dir, String fileName)
{
FileWriter writer;
try
{
writer = new FileWriter(fileName);
writer.write("Hello");
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}

Example append to file:
public static void appendToFile(File dir, String fileName) {
try (FileWriter writer = new FileWriter(new File(dir, fileName), true)) {
writer.write("Hello");
} catch(IOException e) {
e.printStackTrace();
}
}

// write content to sample.txt that is in the directory
try {
Files.write(Paths.get("/Users/NasimAhmed/Desktop/" + filename), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Used - How to append text to an existing file in Java

Related

How do I write to a File stored in a path in Java

I have a Path variable like this:
Path output;
This path is initialized in the main-method.
I want to check if there exists a File in this path
and if thats the case- write a string into that file.
Else create a new File with the given path and write
the string.
//void parseOutput(String s){
//if (file in path exists)
// write(s in file from path)
else
File f = new File(String.valueOf(output));
write String in f
You can try this :
import java.io.*;
class FileDemo {
public static void main(String str[]) {
String path = "E:/myfile.txt";
File file = new File(path);
if(file.exists()) {
System.out.println("File is exist..!!!");
} else {
try {
FileWriter fileWriter = new FileWriter(path);
fileWriter.write("This is my first file..!!");
fileWriter.close();
System.out.println("File has some content..!!");
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}
}
}
If you have a Path, it doesn't really make sense to convert that to a String and use the File constructor.
For checking if a file exists, you can use Files exists.
To add to an existing file, have a look at Files.newBufferedWriter with the APPEND OpenOption set.
Full example:
Path path = Paths.get("/path/to/file.txt");
try (BufferedWriter bufferedWriter = Files.newBufferedWriter(
path, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
PrintWriter printWriter = new PrintWriter(bufferedWriter))
{
printWriter.println("This is a line");
}
You might want to use exists() method in File class. Here's an example which you could use:
public void writeOnFile(String path, String str) throws FileNotFoundException {
PrintWriter out;
File file = new File(path);
if (file.exists()){
out = new PrintWriter(file.getPath());
out.println(str);
}
}

Junk values getting updated to text file

I am trying to update a file with some value. But there are few junk values are also getting updated with the original content while saving. Using the below code.
public class WriteToFile{
public static void main(String[] args){
Path path = Paths.get("C:\\someFile.txt");
String fileContent = new String("someText");
if (Files.exists(path)) {
final File filePath = new File("C:\\someFile.txt");
try {
FileUtils.writeFile(filePath,fileContent);
} catch (final Exception e1) {
// TODO What if writing to the state file fails??
}
}
}
public class FileUploadUtils {
public static void writeFile(final File filePath, final Object
byteFileContent) {
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);
ObjectOutputStream out = new ObjectOutputStream(fileOutputStream)) {
out.writeObject(byteFileContent);
} catch (final IOException io) {
io.printStackTrace();
}
}
}
I am able to write the content to file also, but it is adding some junk characters also. like "’ t SomeText"
The ObjectOutputStream seems to add some values while writing the data to the file.
Why won't you directly use the FileOutputStream you created and pass the data as bytes ?
public static void main(String[] args) {
Path path = Paths.get("C:\\someFile.txt");
String fileContent = new String("someText");
if (Files.exists(path)) {
final File filePath = new File("C:\\someFile.txt");
try {
FileUploadUtils.writeFile(
filePath, fileContent.getBytes());
} catch (final Exception e1) {
// TODO What if writing to the state file fails??
}
}
}
public class FileUploadUtils {
public static void writeFile(final File filePath, final byte[] byteFileContent) {
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
fileOutputStream.write(byteFileContent);
} catch (final IOException io) {
io.printStackTrace();
}
}
}

One of my classes cannot find file that I'm passing through it Java

I'm trying to scan a file with one of my classes but it cannot find the file. The string filename contains the file path. If anyone can help that would be awesome, Thank you!
check.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
FileChooser fc = new FileChooser();
File file = fc.showOpenDialog(null);
if(file != null){
String filename = FileUtils.readFileToString(file);
SpellChecker sc = new SpellChecker(filename);
sc.checker();
//System.out.println(filename);
}
}
});
public SpellChecker(String filename)
{
try (Scanner in = new Scanner(new File(filename));)//go and read the file with the undivided dictionary
{
String word="";
while(in.hasNextLine())//loop through every line
{
word=in.nextLine()+" ";// add the words from that line
}
wtc = fileSplitter(word);
}
catch (FileNotFoundException ex) // if the file is not found where it is specified to be throw exception.
{
System.out.println(E_NOT_FOUND);
System.exit(0);
}
}

Text document is becoming file folder

Here is my class, what I am doing wrong. Why is my text document becoming a file folder. Please explain what is going on and how I can correct it. Thank you
public class InputOutput {
public static void main(String[] args) {
File file = new File("C:/Users/CrypticDev/Desktop/File/Text.txt");
Scanner input = null;
if (file.exists()) {
try {
PrintWriter pw = new PrintWriter(file);
pw.println("Some data that we have stored");
pw.println("Another data that we stored");
pw.close();
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
}
} else {
file.mkdirs();
}
try {
input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
} finally {
if (input != null) {
input.close();
}
}
System.out.println(file.exists());
System.out.println(file.length());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isFile());
System.out.println(file.isDirectory());
}
}
Thanks. The above is my Java class.
You mistakingly assume Text.txt is not a directory name.
mkdirs() creates a directory (and all directories needed to create it). In your case 'Text.txt'
See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs().
It is perfectly fine for a directory to have a . in it.
You could use getParentFile() to get the directory you want to create and use mkdirs() on that.
For additional informations. Here is the différence between the two representaions of files and directories:
final File file1 = new File("H:/Test/Text.txt"); // Creates NO File/Directory
file1.mkdirs(); // Creates directory named "Text.txt" and its parent directory "H:/Test" if it doesn't exist (may fail regarding to permissions on folders).
final File file = new File("H:/Test2/Text.txt"); // Creates NO File/Directory
try {
file.createNewFile(); // Creates file named "Text.txt" (if doesn't exist) in the folder "H:/Test2". If parents don't exist, no file is created.
} catch (IOException e) {
e.printStackTrace();
}
Replace your code:
else {
file.mkdirs();
}
with:
else {
if (!file.isFile()&&file.getParentFile().mkdirs()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Saving files doesn't save a file

I'm creating a program that writes an error log to a file, but when I ask to save that file, just nothing happens (not even exceptions). What do I do wrong?
"Save" button actionListener:
public void actionPerformed(ActionEvent arg0) {
String savePath = getSavePath();
try {
saveFile(savePath);
} catch (IOException e) {
e.printStackTrace();
}
}
And the three file methods:
private String getSavePath() {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(this);
return fc.getSelectedFile().getAbsolutePath();
}
private void saveFile(String path) throws IOException {
File outFile = createFile(path);
FileWriter out = null;
out = new FileWriter(outFile);
out.write("Hey");
out.close();
}
private File createFile(String path) {
String fileName = getLogFileName(path);
while (new File(fileName).exists()) {
fileCounter++;
fileName = getLogFileName(path);
}
File outFile = new File(fileName);
try {
outFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return outFile;
}
private String getLogFileName(String path) {
return "enchantcalc_err_log_" + fileCounter + ".txt";
}
Your getLogFileName(...) function is not doing anything with the path you feed it. Therefore, you are trying to write the file to just enchantcalc_err_log_#.txt (with no actual path). Try this instead:
private String getLogFileName(String path) {
return path + "enchantcalc_err_log_" + fileCounter + ".txt";
}
You are probably just not finding the file.
At the end of your saveFile, try this: After
out.close();
Put a line, like this:
out.close();
System.out.println("File saved to: "+outFile.getAbsolutePath());
You'll then get the mistery path where it was saved.

Categories