Java write to file and save it by fileChooser - java

I am new to java and moving my codes since last two years from VB to java using netbeans 8 .
Now i want to write loop acumalted data to file and last
to save produced file to specific place using FlieChooser below
is my code but i can't see any file in My Desktop when I wrote name in doilog and press enter :
public void SaveToFile() throws IOException {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("test.txt"), "utf-8"))) {
int i=0;
String Data[]=new String[10];
while( i<10 ){
writer.write("Student No :" + i);
Data[i]= "Student No :" + i;
++i;
}
}
int userSelection = db.showSaveDialog(this);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = db.getCurrentDirectory();
String path = fileToSave.getAbsolutePath();
path = path.replace("\\", File.separator);
System.out.println("Save as file: " + path);
}
}

I see a couple problems with this. One, none of the code you're displaying here shows a call to any ".Save()" or copy or move method after choosing the directory. Two, the File object is pointing at a directory, not a file name. Three, your initial Writer object is probably writing test.txt to the directory your .class or .jar file lives in while it's running.
You need to figure out the directory and file name you want to use BEFORE you start writing to the disk.
UPDATE
public void SaveToFile() throws IOException {
int userSelection = db.showSaveDialog(this);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = db.getCurrentDirectory();
String path = fileToSave.getAbsolutePath() + File.separator + "test.txt";
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path), "utf-8"))) {
int i=0;
//String Data[]=new String[10];
while( i<10 ){
writer.write("Student No :" + i);
//Data[i]= "Student No :" + i; // Not sure why Data[] exists?
++i;
}
}
System.out.println("Save as file: " + path);
}
}
I think this is approximate to what you will need. I don't have a java compiler at the moment, so I can't say for sure if that's all good syntax. But there are plenty of Java tutorials online.

Related

Printing an ArrayList using buffered writer in JFrame Form (Java)

I have these three methods and I am trying to write the contents of three lists to a file using the buffered writer.
First Method: To Save File:
public static String showSaveDialog()
{
String fileName = "";
JFileChooser chooser = new JFileChooser();
// Suggesting a name
chooser.setSelectedFile(new File("fileToSave.txt"));
int resultValue = chooser.showSaveDialog(null);
if (resultValue == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getAbsolutePath();
Path = chooser.getSelectedFile().getAbsolutePath();
}
writeToTextFile(fileName, "");
return fileName;
}
Second Method: To write To File:
public static void writeToTextFile(String filePath, String toWrite)
{
BufferedWriter writer = null;
try {
writer = Files.newBufferedWriter(Paths.get(filePath),
StandardOpenOption.CREATE);
writer.write(toWrite);
writer.newLine();
writer.close();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"Saving File Error: " + ex.getMessage(),
"Saving File Error", JOptionPane.ERROR_MESSAGE);
}
}
Third Method: Write Contents of three lists to text file:
public void saveAllQuestions() {
for (String q : questionList){
FileIO.writeToTextFile(FileIO.Path, "$" + q);
for (int i = 0; i < answerList.size(); i++) {
FileIO.writeToTextFile(FileIO.Path,
answerList.get(i) + ", " + correctAnswers.get(i));
}
}
}
When writing to the file the last line is the only one that shows. I am assuming this problem is due to the fact that it is writing to one line only instead of under each other. Can anybody give me some insight please? Thank you
You are opening and closing the file for every line you write. Each time you write a line you are deleting the previous version of the file and replacing it with that one line. You need to open the file, write all the lines, and then close the file.

how to create a file in a specific folder on desktop by default

I am trying to create a file with data inputted by user. But, I want that to be saved on a new folder on desktop every time user runs it. How can I do that?
package my.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class BufferReader {
public static void main(String args[]){
System.out.print("Please enter your text!!: ");
Scanner ip = new Scanner(System.in);
String text = ip.nextLine();
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("text.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.newLine();
writer.close();
System.err.println("Iput of " + text.length() + " characters was saved on Desktop.");
System.out.println("Text you have entered is:" + (ip.nextLine()));
} catch (Exception e) {
System.out.println("Error!");
}
}
}
First you need to know where the desktop is, you can use something like...
File desktop = new File(System.get("user.home") + File.separator + "Desktop");
Now, obviously, this is for Windows, for MacOS, you can follow something similar, but you'd need to verify the location from within the user.home context...
Now you have the desktop path, you could simply create a folder using something like...
File outputFolder = null;
do {
outputFolder = new File(desktop, new SimpleDateFormat("yyyy-MM-dd HH:mm.ss").format(new Date()));
} while (outputFolder.exists());
if (!outputFolder.mkdirs()) {
System.err.println("Failed to create output folder " + outputFolder);
}
Now, this is just creating folders with a timestamp with a second accuracy. It might be nice to give the directory a more meaningful name, but that comes down to needs...
The following example is a little more complicated, this basically lists all the directories in the desktop, which start with the predetermined predix.
It then loops throughs and determines the max number suffix and create a new directory with the next number in the sequence, this means that if you delete a directory, it won't try and overwrite an existing directory...
String prefix = "Test";
File[] folders = desktop.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory()
&& pathname.getName().startsWith(prefix);
}
});
System.out.println(folders.length);
int max = 0;
for (File folder : folders) {
String name = folder.getName();
name = name.substring(prefix.length()).trim();
System.out.println(name);
max = Math.max(max, Integer.parseInt(name));
}
max++;
String suffix = String.format("%04d", max);
File output = new File(desktop, prefix + " " + suffix);
System.out.println(output);
if (!output.exists() && !output.mkdirs()) {
System.out.println(output + " not created");
}

Java reading text file

I have a question about txt file in the Java
When I have to read the text file, i have to point out the path.
However, txt file is in the same folder.
What need to do is...
testing readingoption filename.
testing : class name
readoption : option for reading file
filename: file name that same folder.
However, I don't want to use path to pointing out the file which means that I want to read the text file without using "C:/Users/myname/Desktop/myfolder/" in my code.
does anybody know how to do it ?
thanks.
public class testing{
private static boolean debug = true;
public static void main(String args [])
{
if(args.length == 0)
{// if you do nothing
if(debug == true)
{
System.out.println(args);
}
System.err.println("Error: Missing Keywords");
return;
}
else if(args.length == 1)
{// if you miss key word
if(debug == true)
{
System.out.println(args);
}
System.err.println("Error: Missing filename");
return;
}
else
{// if it is fine
String pathes = "C:/Users/myname/Desktop/myfolder/";// dont want to use this part
if(debug == true)
{
System.out.println("Everthing is fine");
System.out.println("Keyword :" + args[0]);
System.out.println("File name :" + args[1]);
}
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(pathes + "bob.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
Change this line String pathes = "C:/Users/myname/Desktop/myfolder/"; to:
String pathes = args[1];
and this line FileInputStream fstream = new FileInputStream(pathes + "bob.txt"); to:
FileInputStream fstream = new FileInputStream(pathes);
If you put text file into i.e. "myfolder" in your java project your path should be like this:
String pathes = "/myfolder/bob.txt";
FileInputStream fstream = new FileInputStream(pathes);
Load the path of the file from a .properties file (use the java.util.Properties class), or pass it as a parameter from commandline (in your main String[] argument).
Either way, your code that processes the file must not do it, it must be done in the outside. Your processing code receives the file path from the method calling it, so you do not need to change if you decide to use another method (v.g., a GUI).
You can use "." for the actual Path and add the system dependend file seperator like:
FileInputStream fstream = new FileInputStream("."+System.getProperty("file.separator")+"bob.txt");

Java - how to get all the file names in a folder

I'm not a really good Java programmer and I need to know how I can print out all the files in a single folder. See the code below:
for(int i=0;i<folder.number_of_files;i++){
System.out.println(filename[i]);
}
Thanks for your time
Easiest way would be to use File#listFiles. And if you're using Java 7, see this for changes to the file I/O library. For instance,
File folder = ...;
for(File f : folder.listFiles())
{
System.out.println(f.getName());
}
Note that this will not grab the contents of any sub-folders within the folder directory.
File file = new File("C:\\");
File[] files = file.listFiles();
for (File f:files)
{
System.out.println(f.getAbsolutePath());
}
listFiles() has more options. see the documentation here
If you also want to check subfolders below example runs a recursive and check all files under Desktop and its subfolders and writes into a list.
private static String lvl = "";
static BufferedWriter bw;
private static File source = new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\New folder\\myTest.txt");
public static void main(String[] args) throws IOException {
bw = new BufferedWriter(new FileWriter(source));
checkFiles(new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop"), 0);
bw.flush();
bw.close();
lvl = null;
}
static void checkFiles(File file, int level) throws IOException{
if(!file.exists()){
return;
}
for(String s:file.list()){
if(new File(file.getPath() + "\\" + s).isDirectory()){
bw.newLine();
bw.write(lvl + "Directory: " + s);
lvl += " ";
checkFiles(new File(file.getPath() + "\\" + s), level+1);
}else{
bw.newLine();
bw.write(lvl + "File: " + s);
}
}
}
}

Can't read lines from a text file

I have a method like this:
public int getIncrement() {
String extractFolder = "/mnt/sdcard/MyFolder";
boolean newFolder = new File(extractFolder).mkdir();
int counter = 0;
try {
File root = new File(extractFolder);
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.txt");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
Scanner scanner = new Scanner(new FileInputStream(gpxfile.getAbsolutePath()), "UTF-8");
Log.i("PATH: ", extractFolder + "/gpxfile.txt");
while(scanner.hasNextLine()) {
String inc = scanner.nextLine();
counter = Integer.parseInt(inc);
Log.i("INSIDE WHILE: ", Integer.toString(counter));
}
counter++;
out.write(Integer.toString(counter));
out.close();
}
} catch (IOException e) {
Log.e("GEN_PCN: ", "Could not write file " + e.getMessage());
}
return counter;
}
What I am trying to accomplish is returning the content of this file, and increment the integer by 1. But it seems that I can't get in the while loop, because LogCat doesn't print out anything. Yes, am sure that the path is correct.
I guess the constructor of FileWriter gpxwriter has already blanked out the file by the time the Scanner is created, so the file is empty and hasNextLine returns false. Why do you open a file for writing when you want to read it?
From what I can tell the file doesn't exist. Try adding gpxfile.createNewFile()
To get a little more in depth, creating a File instance, does not create a file on the file system.
So, this line -> File gpxfile = new File(path, filename);
is not sufficient to create the file on the sd card. You must follow it with
gpxfile.createNewFile() which quoting the docs says:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
OK I MARK YOUR FILE NAME
Just add a BACKSLASH in extractFolder at END
v
v
v
String extractFolder = "/mnt/sdcard/MyFolder/";
^ // <--- HERE
^
^
Because File gpxfile = new File(root, "gpxfile.txt"); doesn't have BackSlash / as Log have
Just try Once Following:
while(scanner.hasNextLine()) {
String inc = scanner.nextLine();
// // counter = Integer.parseInt(inc);
Log.i("INSIDE WHILE: ", inc);
System.out.println("Next Line ::"+inc); // Also check this
}

Categories