This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reading the java files from the folder
I have developed a java code that reads files from the folder chosen by the user. It displays how many lines of code are in each file, it reads only .java filesonly and final outcome is shown on console , I was thinking that output to be get displayed on console but along with a text file conataing the same information to be get stored on desktop also, please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console , here is my piece of code...
public static void main(String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{ Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
int totalLineCount = 0;
File[] files = directory.listFiles(new FilenameFilter(){
#Override
public boolean accept(File directory, String name) {
if(name.endsWith(".java"))
return true;
else
return false;
}
}
);
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
totalLineCount += lineCount;
}
} }
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);
}
}
output that is displayed on console is to be stored in a text file on desktop also, please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console
I'd advice you to ask questions more precisely. From what I understand from your question, you want to write some information to a text file. To do this all you have to do is this -
try{
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Desktop//output"+new Timestamp(date.getTime())+".txt"));
out.write("some information");
out.close;
}catch(IOException e){
e.printStackTrace();
}
So in your code inplace of System.out.println(); statements you can use out.write()
statements to write to a text file.
Hope this helps you.
Related
This is my java code to find the locations of files inside the directory and write them into a txt file as the output ,but after compilation the contents are not writing into txt file. please give me some solution.
public void listFilesAndFilesSubDirectories(String directoryName)
{
File directory = new File(directoryName);
List<String> list=new ArrayList<String> ();
//get all the files from a directory
if(directory.exists()){
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
if(file.getName().endsWith(".c")==true || file.getName().endsWith(".h")==true){
// System.out.println(file.getAbsolutePath());
list.add(file.getAbsolutePath());
}
} else if (file.isDirectory()){
listFilesAndFilesSubDirectories(file.getAbsolutePath());
}
else break;
}
try{
FileWriter fw=new FileWriter("C:/Users/Public/afreen/module.txt");
BufferedWriter out = new BufferedWriter(fw);
for(String str: list)
{
System.out.println(str);
out.write(str);
}
out.flush();
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success....");
}
else
{
System.out.println("The directory is not exist , please enter a valid path");
}
}
The above code will take the input as the path for directory and finds the location of files which I want.But the locations are not able to write into txt file,I am not abel to find the actual reason ,please help me out to find the solution of it.
Each time your method gets called (recursively) creates a new list and add the directory name to it but that list is not the one you are printing from, try to use a shared resource. for example use a global variable or etc.
i am having an issue opening a file and getting my program to read the integers in the file. In the code below, to get my car data i can either have it randomly generated to get my duration time for a car, and the chance that a car arrives. Or read integers from a file. The file is already given by our professor and her is what is in the file:
37259 9819
46363 22666
46161 79934
5693 31416
91459 8272
72792 9493
83603 8372
77842 64629
84792 747
1299 178
Apparently I am unable to open the file even using the absolute path, or data = dataFile.nextInt() isn't the correct format to use. Any help would be appreciated i am absolutely stumped on this part, my whole program works but files are my Achilles heel.
if (dataSource == 1) {
System.out.printf("Enter a filename \t :");
String aName = input.next();
java.io.File file = new java.io.File(aName);
try {
dataFile = new Scanner(file);
} catch (Exception e) {
System.out.println("Can't open file");
}
} else {
dataRandom = new Random();
System.out.println("Is Random Active");
}
input.close();
}
private void getCarData() {
if (dataSource == 1) {
int data1;
int data2;
data1 = dataFile.nextInt();
data2 = dataFile.nextInt();
anyNewArrival = (((data1%100) + 1) <= chancesOfArrival);
serviceDuration = (data2%maxDuration) + 1;
System.out.println("New Car has arrived with Duration Time: " + serviceDuration);//}
}
If running from Netbeans or Ecplise, you can use the relative path "text.txt" And make sure your file structure is something like this
ProjectRoot
src
build
text.txt
So I have the following code (which has been shamelessly copied from a tutorial so I can get the basics sorted), in which it asks the player to load their game (text-based adventure game)
but I need a way to display all the saved games in the directory. I can get the current directory no worries. Here is my code:
public void load(Player p){
Sleep s = new Sleep();
long l = 3000;
Scanner i = new Scanner(System.in);
System.out.println("Enter the name of the file you wish to load: ");
String username = i.next();
File f = new File(username +".txt");
if(f.exists()) {
System.out.println("File found! Loading game....");
try {
//information to be read and stored
String name;
String pet;
boolean haspet;
//Read information that's in text file
BufferedReader reader = new BufferedReader(new FileReader(f));
name = reader.readLine();
pet = reader.readLine();
haspet = Boolean.parseBoolean(reader.readLine());
reader.close();
//Set info
Player.setUsername(name);
Player.setPetName(pet);
Player.setHasPet(haspet);
//Read the info to player
System.out.println("Username: "+ p.getUsername());
s.Delay(l);
System.out.println("Pet name: "+ p.getPetName());
s.Delay(l);
System.out.println("Has a pet: "+ p.isHasPet());
} catch(Exception e){
e.printStackTrace();
}
}
}
File currentDirectory = new File(currentDirectoryPath);
File[] saveFiles = currentDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
You can first get a File object for the directory:
File ourDir = new File("/foo/bar/baz/qux/");
Then by checking ourDir.isDirectory() you can make sure you don't accidentally try to work on a file. You can handle this by falling back to another name, or throwing an exception.
Then, you can get an array of File objects:
File[] dirList = ourDir.listFiles();
Now, you may iterate through them using getName() for each and do whatever you need.
For example:
ArrayList<String> fileNames=new ArrayList<>();
for (int i = 0; i < dirList.length; i++) {
String curName=dirList[i].getName();
if(curName.endsWith(".txt"){
fileNames.add(curName);
}
}
This should work:
File folder = new File("path/to/txt/folder");
File[] files = folder.listFiles();
File[] txtFiles = new File[files.length];
int count = 0;
for(File file : files) {
if(file.getAbsolutePath().endsWith(".txt")) {
txtFiles[count] = file;
count++;
}
}
It should be pretty self explanatory, you just need to know folder.listFiles().
To trim down the txtFiles[] array use Array.copyOf.
File[] finalFiles = Array.copyOf(txtFiles, count);
From the docs:
Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.
I have developed a java code that reads files from the folder chosen by the user. It displays how many lines of code are in each file, it reads only .java filesonly and final outcome is shown on console , I was thinking that output to be get displayed on console but along with a text file conataing the same information to be get stored on desktop also, please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console , here is my piece of code...
public static void main(String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{ Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
int totalLineCount = 0;
File[] files = directory.listFiles(new FilenameFilter(){
#Override
public boolean accept(File directory, String name) {
if(name.endsWith(".java"))
return true;
else
return false;
}
}
);
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
totalLineCount += lineCount;
}
} }
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);
}
}
Now the idea in my mind id for this logic
1) construct the file name you want to use
2) open the file for write
3) each time you call a System.out.println(), make a similar call to write the same message to the file
4) when you are all done, make sure you close the file handle.
I have an rough idea something like this
try{
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Desktop//output"+new Timestamp(date.getTime())+".txt"));
out.write("some information");
out.close;
}catch(IOException e){
e.printStackTrace();
}
please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console
As far as I can tell, this is the only thing you are actually asking:
Please advise how to that and the name of the file that is generated its name is to be based on timestamp. Lets assume that name of the output file would be 'output06282012' ...
The simple answer is:
String fileName = "output" + new Date().getTime();
You then go on to say:
.... and that text file should contain the same information that is shown on the console
You've got two choices:
You can change where System.out goes to by calling System.setOut(...). (Check the javadoc for details.)
You can create a PrintWriter or PrintStream wrapper for your file stream and write to that instead of writing to System.out.
In my opinion, it is a bad idea to use System.setOut(...) unless you've got no choice. It is a "global action" that affects the entire application. It is better to pass the writer that you want to use as a parameter ...
could you please sow in code as I have done that will clear the understanding
Sorry, I don't write people's programs for them (unless it is an interesting problem!). You need to write and debug the code yourself, using the information provided in the relevant javadocs. You can find the Java documentation online on the Oracle website: http://docs.oracle.com/javase/7/docs/
I have a method that get text from a JTextArea, create a file and write text on it as code below:
public void createTxt() {
TxtFilter txt = new TxtFilter();
JFileChooser fSave = new JFileChooser();
fSave.setFileFilter(txt);
int result = fSave.showSaveDialog(this);
if(result == JFileChooser.APPROVE_OPTION) {
File sFile = fSave.getSelectedFile();
FileFilter selectedFilter = fSave.getFileFilter();
String file_name = sFile.getName();
String file_path = sFile.getParent();
try{
if(!sFile.exists()) {
sFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
out.write(jTextArea1.getText());
out.close();
JOptionPane.showMessageDialog(null, "Warning file • " + file_name + " • created succesfully in \n" + file_path);
} else {
String message = "File • " + file_name + " • already exist in \n" + file_path + ":\n" + "Do you want to overwrite?";
String title = "Warning";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION){
sFile.delete();
sFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
out.write(jTextArea1.getText());
out.close();
JOptionPane.showMessageDialog(null, "File • " + file_name + " • overwritten succesfully in \n" + file_path);
}
}
}
catch(IOException e) {
System.out.println("Error");
}
}
}
and a txt file filter
public class TxtFilter extends FileFilter{
#Override
public boolean accept(File f){
return f.getName().toLowerCase().endsWith(".txt")||f.isDirectory();
}
#Override
public String getDescription(){
return "Text files (*.txt)";
}
}
The file filter for txt works fine but what I want is to add ".txt" extension when I type file name.
How to I have to modify my code?
I just use this
File fileToBeSaved = fileChooser.getSelectedFile();
if(!fileChooser.getSelectedFile().getAbsolutePath().endsWith(suffix)){
fileToBeSaved = new File(fileChooser.getSelectedFile() + suffix);
}
UPDATE
You pointed me out that the check for existing files doesn't work. I'm sorry, I didn't think of it when I suggested you to replace the BufferedWriter line.
Now, replace this:
File sFile = fSave.getSelectedFile();
with:
File sFile = new File(fSave.getSelectedFile()+".txt");
With this replacement, it isn't now needed to replace the line of BufferedWriter, adding .txt for the extension. Then, replace that line with the line in the code you posted (with BufferedWriter out = new BufferedWriter(new FileWriter(sFile)); instead of BufferedWriter out = new BufferedWriter(new FileWriter(sFile+".txt"));).
Now the program should work as expected.
I forgot to mention that you have to comment the line:
sFile.createNewFile();
In this way, you're creating an empty file, with the class File.
Just after this line, there is: BufferedWriter out = new BufferedWriter(new FileWriter(sFile));.
With this line, you are creating again the same file. The writing procedure is happening two times! I think it's useless to insert two instructions that are doing the same task.
Also, on the BufferedWriter constructor, you can append a string for the file name (it isn't possible on File constructor), that's the reason why I added +".txt" (the extension) to sFile.
This is a utility function from one of my programs that you can use instead of JFileChooser.getSelectedFile, to get the extension too.
/**
* Returns the selected file from a JFileChooser, including the extension from
* the file filter.
*/
public static File getSelectedFileWithExtension(JFileChooser c) {
File file = c.getSelectedFile();
if (c.getFileFilter() instanceof FileNameExtensionFilter) {
String[] exts = ((FileNameExtensionFilter)c.getFileFilter()).getExtensions();
String nameLower = file.getName().toLowerCase();
for (String ext : exts) { // check if it already has a valid extension
if (nameLower.endsWith('.' + ext.toLowerCase())) {
return file; // if yes, return as-is
}
}
// if not, append the first extension from the selected filter
file = new File(file.toString() + '.' + exts[0]);
}
return file;
}
I've done this function for this purpose :
/**
* Add extension to a file that doesn't have yet an extension
* this method is useful to automatically add an extension in the savefileDialog control
* #param file file to check
* #param ext extension to add
* #return file with extension (e.g. 'test.doc')
*/
private String addFileExtIfNecessary(String file,String ext) {
if(file.lastIndexOf('.') == -1)
file += ext;
return file;
}
Then you can use the function for example in this way :
JFileChooser fS = new JFileChooser();
String fileExt = ".txt";
addFileExtIfNecessary(fS.getSelectedFile().getName(),fileExt)