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.
Related
I tried uploading a file, and placed the file in the "public / images" directory and it worked, but the file I uploaded was zero in size and certainly couldn't be opened
public Result upload() throws IOException {
Http.MultipartFormData<File> requestBody = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> profile_pic = requestBody.getFile("profile_pic");
String dirPath = "public/images/";
if(profile_pic != null) {
String name = profile_pic.getFilename();
File file = profile_pic.getFile();
System.out.println(file);
File theDir = new File(dirPath);
if (!theDir.exists()) {
boolean result = false;
try {
theDir.mkdirs();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
try {
File filex = new File(dirPath + name.toLowerCase());
filex.createNewFile();
file.renameTo(filex);
}catch (Exception e) {
// TODO: handle exception
}
return ok("File uploaded ");
}else {
return badRequest("Eroor");
}
}
this is my file after upload
I think creating a new file and renaming your old file to that name may cause trouble. I would recommend using the move method, see docs here.
Does your System.out.println(file); print what looks like a normal png 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();
}
}
}
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);
}
}
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
I have been trying to call a method in another class that instantiates a new JFileChooser dialog. Everything seems to work ok except that the APPROVE_OPTION code
int userSelection = chooser.showSaveDialog(chooser);
if (userSelection == JFileChooser.APPROVE_OPTION) {
System.out.println("File saved " + chooser.getSelectedFile().getName());
}
doesn't appear to work.
Below is the method contains the createFile method that has the JFileChooser within
public class TextFileHandler {
private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
private static JFileChooser chooser;
private static int userSelection;
public void createFile(String shiftPattern) {
chooser = new JFileChooser();
chooser.setSelectedFile(new File(shiftPattern + "_export"));
chooser.setDialogTitle("Save shift pattern to CSV format");
FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV", "csv");
chooser.setFileFilter(filter);
int userSelection = chooser.showSaveDialog(chooser);
if (userSelection == JFileChooser.APPROVE_OPTION) {
System.out.println("File saved " + chooser.getSelectedFile().getName());
}
}
The below file is an excerpt of the class that calls the above method from a button press action.
else if (action.equals("EXPORT_CSV_BUTTON")) {
TextFileHandler textFile = new TextFileHandler();
String temp = copyPatternController.getShiftPatCode();
messageShow(new Integer(TextFileHandler.getUserSelection()).toString() + " and "
+ (TextFileHandler.getChooser().APPROVE_OPTION)); //for debugging
textFile.createFile(temp);
FileWriter fw = null;
try {
File file = new File(temp + "_export.csv");
fw = new FileWriter(file);
fw.append("testing");
} catch (IOException e) {
System.out.println("Error in writing csv file !!!");
e.printStackTrace();
} finally {
try {
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The save dialog appears ok but when i press save the dialog closes and nothing is created. Appreciate any ideas
In the EXPOPRT_CSV_BUTTON I was missing a getSelectedFile() call.
File file = new File(TextFileHandler.getChooser().getSelectedFile().getPath() + ".csv");
The creates the file with no problems. I have also refactored my obfuscated code thank you for pointing that out.