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);
}
}
}
}
Related
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.
My program displays elements read from a text file. The text files will be stored in a folder found in the package folder containing the .java and .class files so they can be embedded in the jar.
I'm trying to get the application to read the text files properly for both situations
Running from the IDE (Netbeans)
Running from the JAR
Currently I can do point one with no problem, but the code reads using File where as the way I am seeing how to do it with Jars is using InputStream.
The functions which work for the IDE runs
public void loadWidgets() {
ArrayList<String> results = new ArrayList<>();
String dir = new File("").getAbsolutePath() + "/src/Creator/textFiles/widgets/;
System.out.println(dir);
getWidgetFiles(dir, results);
results.stream().forEach((s) -> {
readFile(s); // given a string and it opens the file using a Scanner
});
updateWidgetVariables(); // gui updates
}
public void getWidgetFiles(String dirName, ArrayList<String> filePaths) {
File directory = new File(dirName);
File[] files = directory.listFiles();
for (File file : files) {
if (file.isFile()) {
filePaths.add(file.getName() + "," + file.getAbsolutePath());
} else if (file.isDirectory()) {
getWidgetFiles(file.getAbsolutePath(), filePaths);
}
}
}
So I have a bunch of text files organized by the type of widget it is, so I am running through the /widgets/ directory to find all the text files.
The problem I'm having is how I can go through the directories and files of a Jar? Can they be converted to a file, or read into a string?
I got this code from this question and it can read the files, but I dont know how I can open them using a new Scanner(file); code
CodeSource src = WidgetPanel.class.getProtectionDomain().getCodeSource();
try {
System.out.println("Inside try");
List<String> list = new ArrayList<>();
if (src != null) {
URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream(jar.openStream());
ZipEntry ze = null;
System.out.println(jar.getPath());
System.out.println(zip.getNextEntry());
while ((ze = zip.getNextEntry()) != null) {
String entryName = ze.getName();
System.out.println("Entry name: " + entryName);
if (entryName.startsWith("Creator/textFiles/widgets") && entryName.endsWith(".txt")) {
list.add(entryName);
System.out.println("Added name: " + entryName);
}
}
list.stream().forEach((s) -> {
readFile(s);
});
updateWidgetVariables();
} else {
System.out.println("Src null");
}
}catch (IOException e) {
System.out.println(e.getMessage());
}
Try and obtain a FileSystem associated with your source; the matter then becomes pretty simple. Here is an illustration of how to read, as text, all files from a given FileSystem:
private static final BiPredicate<Path, BasicFileAttributes> FILES
= (path, attrs) -> attrs.isRegularFile();
private static void readAllFilesAsText(final List<Path> paths)
throws IOException
{
for (final Path path: paths)
try (
final Stream<String> stream = Files.lines(path);
) {
stream.forEach(System.out::println);
}
}
private static List<Path> getAllFilesFromFileSystems(final FileSystem fs,
final String pathPrefix)
{
final Path baseDir = fs.getPath(pathPrefix);
try (
final Stream<Path> files = Files.find(baseDir, Integer.MAX_VALUE,
FILES);
) {
return files.collect(Collectors.toList());
}
}
Why the mix of "old style" for loops and "new style" lambdas: it is because lambdas just don't handle checked exceptions... Which means you have to do it. For a workaround, see here.
But the gist of it here is to be able to create a FileSystem out of your sources, and you can do it; yes, you can read jars as such. See here.
I was able to find a solution using the functions I already had.
I first check to see if the text file can be found normally (Run from an IDE). If a file not found exception occurs, it sets ide = false so it tries to read from the jar.
public void loadWidgets() {
boolean ide = true;
String path = "textFiles/widgets/";
ArrayList<String> results = new ArrayList<>();
String dir = new File("").getAbsolutePath() + "/src/Creator/" + path;
try {
getWidgetFiles(dir, results);
results.stream().forEach((s) -> {
readFile(s);
});
updateWidgetVariables();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
ide = false;
}
if (!ide) {
CodeSource src = WidgetPanel.class.getProtectionDomain().getCodeSource();
try {
List<String> list = new ArrayList<>();
if (src != null) {
URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream(jar.openStream());
ZipEntry ze = null;
while ((ze = zip.getNextEntry()) != null) {
String entryName = ze.getName();
if (entryName.startsWith("Creator/textFiles/widgets") && entryName.endsWith(".txt")) {
// Wouldnt work until i added the "/" before the entryName
list.add("/"+ entryName);
System.out.println("Added name: " + entryName);
}
}
list.stream().forEach((s) -> {
readJarFile(s);
});
updateWidgetVariables();
} else {
System.out.println("Src null");
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
I then created a new readFile function for reading from a Jar
public void readJarFile(String result) {
String name = result.substring(result.lastIndexOf("/") + 1);
String entireWidget = "";
String line;
ArrayList<String> vars = new ArrayList<>();
int begin, end;
InputStream loc = this.getClass().getResourceAsStream(result);
try (Scanner scan = new Scanner(loc)) {
while (scan.hasNextLine()) {
line = scan.nextLine();
entireWidget += line;
while (line.contains("`%")) {
begin = line.indexOf("`%");
end = line.indexOf("%`") + 2;
vars.add(line.substring(begin, end));
//System.out.println("Variable added: " + line.substring(begin, end));
line = line.substring(end);
}
}
}
System.out.println(name + ": " + entireWidget);
Widget widget = new Widget(name, vars, entireWidget, result);
widgetList.put(name, widget);
}
Most of this answer is thanks to this question
I have a text file in the same location as my .jar program:
Main Folder:
|_ myJar.jar
|_ myText.txt
When I run the .jar file I would like it to read the contents of myText.txt, however with the path set as String fileName = "./Paths.txt"; it still doesn't read the file. I believe it's trying to read the Paths.txt file from inside the jar.
I tried other solutions, none seem to tell the program to read the Paths.txt file from outside of the jar file, so any help would be greatly appreciated.
Code:
public static void readFile() {
String fileName = "./Paths.txt";
BufferedReader br;
String line;
//Attempts to read fileName
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
try {
// Starts reading the file and adding values to linked hashmap
while ((line = br.readLine()) != null) {
String[] lineSplit1 = line.split("#");
String lineKey = lineSplit1[0];
String lineValue = lineSplit1[1];
hm.put(lineKey, lineValue);
}
} catch(Exception e3) {
errorMessage("Error when trying to read the file and add "
+ "the values to a hashmap");
}
//Attempts to close fileName
try {
br.close();
} catch(IOException e1 ) {
System.out.println("Messed up while trying to close buffered reader");
System.out.println(e1);
}
} catch (FileNotFoundException e1) {
errorMessage("The file " + fileName + " does not exist"
+ "\nI have created the file for you.");
try {
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println("");
writer.close();
} catch(Exception e2) {
errorMessage("Error while trying to create " + fileName);
}
}
}
I suppose, you can get a full path to your file, just need to initialize it, via your Class, which should be packaged in myJar.jar. Just change YourClass in the example to some real Class from your jar.
public static void readFile() {
File file = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().getFile());
String fileName = file.getParent() + File.separator + "Paths.txt";
...
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");
}
public static void main(String[] args)
{
try
{
File dir = new File("D:\\WayneProject\\Logs");
if(dir.isDirectory())
{
for(File child: dir.listFiles()) //NOT WORKING AFTER 1 ITERATION
{
if(child.isFile())
{
String currentFile = child.getName();
String[] fileOutput = currentFile.split("\\.");
processFile(currentFile,fileOutput[0]);
}
}
}
}
Please check comments. Iterating over files giving File not found exception (for the second iteration) even when the file is there in the dir. Can you please tell me why? Thanks
My other function. The fileOutput is used to set the name of the destination file:
public static void processFile(String fileName, String fileOutput)
{
try
{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String str = null;
File fileDest1 = new File("D:\\" + fileOutput + "1.csv");
BufferedWriter wr1 = new BufferedWriter(new FileWriter(fileDest1));
File fileDest2 = new File("D:\\" + fileOutput + "2.csv");
BufferedWriter wr2 = new BufferedWriter(new FileWriter(fileDest2));
wr1.write("Date, Memory Free\n");
wr2.write("Date, %Idle\n");
while((str=br.readLine()) != null)
{
String[] st = str.split("\\s+");
if (st[0].equals("MemFree:"))
{
wr1.write(st[1] + ",\n");
}
if(isDouble(st))
{
wr2.write(st[6] + "," + "\n");
}
if(isDate(st[0]))
{
String subStr = str.substring(0, 20);
wr1.write(subStr + ",");
wr2.write(subStr + ",");
}
}
br.close();
wr1.close();
wr2.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
I suspect this is the problem in two ways:
String currentFile = child.getName();
String[] fileOutput = currentFile.split(".");
processFile(currentFile,fileOutput[0]);
getName() only returns the last part of the filename - the name within the directory. So unless your processFile part then puts the directory part back, you're asking it to process a file within the current working directory.
split takes a regular expression. By providing . as the regular expression, you're splitting on every character. I strongly suspect you actually want currentFile.split("\\.") which will actually split on a dot.
You haven't given any indication of what processFile is doing, but I suspect at least one of those is the root cause, and probably both.
It's worth taking a step back and looking at your diagnostics here, too. If you look at what's being passed to processFile you should be able to understand what's wrong - that it's not a problem with the file system, it's a problem with how you're computing the arguments to processFile. Being able to diagnose errors like this is a very important part of software development.
Your code works fine for me. What error you might be having is in processFile function you are creating a file object from the fileName, which is not existing. Then might be trying to read the contents of the file which might be throwing you FileNotFoundException. just comment processFile function and your code will work.