Junk values getting updated to text file - java

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

Related

Want a code to be written without throwing exception

I have the below piece of code.
import java.io.*;
public class FileTest {
public static void main(String[] args) throws IOException {
WriteLinesToFile("miss.txt","This is a special file");
}
public static void WriteLinesToFile(String outputFileName, String lineConverted) throws IOException {
File f = new File(outputFileName);
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
}
I need the same logic, without throwing exception. Could someone tell me how to do this?
You could handle your exception with a try{} catch(IOException e){}
But it's important to handle the exception, because otherwise your program will do something, but not what you want.
import java.io.*;
public class FileTest {
public static void main(String[] args)
{
writeLinesToFile("miss.txt", "This is a special file");
}
public static void writeLinesToFile(String outputFileName, String lineConverted){
File f = new File(outputFileName);
try {
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
catch(IOException e){
//Handle your error
}
}}
But you can't cut out the exceptions at all, because handling files in java throws always exceptions (For example if the file could not be found).

Search for a file and append to it

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

My deflater class works incorecctly

My compression class works incorrectly. When i am trying to compress simple file that contains sentence "something", compressed and uncompressed returns something other. Here is my deflating code:
public static void inflate(String arg) throws Exception {
try {
FileInputStream fin = new FileInputStream(arg);
InflaterInputStream in = new InflaterInputStream(fin);
FileOutputStream fout = new FileOutputStream("def.txt");
int i;
while ((i = in.read()) != -1) {
fout.write((byte) i);
fout.flush();
}
fin.close();
fout.close();
in.close();
} catch (Exception e) {
System.out.println(e);
}
new File(arg).delete();
new File("def.txt").renameTo(new File(arg));
}
public static void deflate(String arg) throws Exception {
try {
FileInputStream fin = new FileInputStream(arg);
FileOutputStream fout = new FileOutputStream("def.txt");
DeflaterOutputStream out = new DeflaterOutputStream(fout);
int i;
while ((i = fin.read()) != -1) {
out.write((byte) i);
out.flush();
}
fin.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
new File(arg).delete();
new File("def.txt").renameTo(new File(arg));
}
I call it using
public static void main(String[] args) {
try {
Main.deflate(args[0]);
Main.inflate(args[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So how to fix my code? I think that problem is not in deflating code.
Your code does seem to work as expected.
Running it on a text file containing the word 'something' returns an identical file.
To confirm that the output is the same, try editing the following lines:
Test.inflate("def.txt");
which is in your main function and
FileOutputStream fout = new FileOutputStream("output.txt");
from your inflate function.
Then comment out the following lines in both your deflate() and inflate() functions
//new File(arg).delete();
//new File("def.txt").renameTo(new File(arg));
The program will now take an input file, I used input.txt with the word 'something' as per your example, and create a deflated file def.txt and an output.txt file that is created by inflating def.txt.
The output file should match the input file exactly, while the deflated file should be different. If not, there must be some further information about the program that is missing.

Update properties file values with form values

I am having a jsp file in which I load the existing values present in properties file. When the user edit the existing value and submit the form, the properties file must be updated with that values. Can anyone help me with this? I am using only java.
FileInputStream in = new FileInputStream("Example.properties");
Properties props = new Properties();
props.load(in);
Now Update it
FileOutputStream outputStream = new FileOutputStream("Example.properties");
props.setProperty("valueTobeUpdate", "new Value");
props.store(outputStream , null);
outputStream .close();
Another way of achieving same is explained at
http://crunchify.com/java-properties-files-how-to-update-config-properties-file-in-java/
PropertiesConfiguration config = new PropertiesConfiguration("/Users/abc/Documents/config.properties");
config.setProperty("Name", "abcd");
config.setProperty("Email", "abcd#gmail.com");
config.setProperty("Phone", "123456");
config.save();
here is an example of how to update your properties file :
public class PropertyManager {
private static Properties prop = new Properties();
private static String PROPERTY_FILENAME = "config.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.get("myProperty"));
updateProperty("myProperty", "aSecondValue");
}
public static void loadProperty(){
InputStream input = null;
try {
input = new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(String name, String value){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty(name, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I let you change "new Properties", by the way you retrieve it.

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