Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to know if it's possible to do this:
i've some .txt file in a directory in my filesystem
i would like to write a java code that does this:
Automatically read all the files in the directory
Give me a output
Exists some library? or it's just a code problem?
It's possible?
Thanks
Reads & prints the content
public static void main(String[] args) {
List<String> li=new TestClass().textFiles("your Directory");
for(String s:li){
try(BufferedReader br = new BufferedReader(new FileReader(s))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} catch (IOException e) {
e.printStackTrace();
}
}
}
For getting all Text files in the Directory
List<String> textFiles(String directory) {
List<String> textFiles = new ArrayList<String>();
File dir = new File(directory);
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.add(file.getPath());
}
}
return textFiles;
}
Of course it's possible. You need to look at File, Reader classes. A useful method is File#listFiles. Happy coding.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to be able to go through a folder containing files and display the files that have been specified. I currently have it hard coded... Cc
public void searchResult(String a) throws IOException {
FileReader inputFile;
a = "C:\\IO\\Project.txt";
try {
inputFile = new FileReader(a);
BufferedReader br = new BufferedReader(inputFile);
while ((str = br.readLine()) != null) {
searchResult.setText(str);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(SearchResults.class.getName()).log(Level.SEVERE, null, ex);
}
}
Please, I need something more dynamic.
i currently have it hard coded
Do you understand how passing parameters work?
public void searchResult(String a) throws IOException
{
a = "C:\\IO\\Project.txt";
try {
inputFile = new FileReader(a);
What is the point of hardcoding the value of "a". The point of using parameters is to pass the file name as a parameter to you method.
So the code should simply be:
public void searchResult(String a) throws IOException
{
try {
inputFile = new FileReader(a);
Also the following makes no sense:
while ((str = br.readLine()) != null) {
searchResult.setText(str);
Every time you read a new line of text you replace the previous line of text. You need to append(...) the text.
Or, the better solution is to just use the read(...) method of the JTextArea to load data from the file.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am very new to Java and I am working on a project. I have been told that in order to complete this project I will need to save a file into a hash map. This file contains words and their abbreviation so later on I want to be able to search for a particular word and then return the abbreviation for it. I have been able to make the hash map and access the file, but I'm stuck on how to save it into the hash map.
public Shortener() {
Map<String, String> abbrevFile = new HashMap<String, String>();
File file = new File("C:\\abbreviations.txt");
I would use a properties file as it's an existing format.
e.g.
Hello=Hi
Abreviation=Abr
such as
Properties p = new Properties();
p.load(file);
abbrevFile.putAll((Map) p);
To look up the map you can do
public String lookup(String word) {
return abbrevFile.get(word);
}
Here is an example of reading a file and storing the data in the hashmap
static HashMap<String, String> wordList = new HashMap<>();
public static void main(String[] args) {
readFile(new File("words.txt"));
}
private static void readFile(File file) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split("-");
wordList.put(args[0], args[1]);
}
System.out.println("Populated list with "+ wordList.size() + " words.");
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Providing your format is in the following format
word-abbreviation
word-abbreviation
word-abbreviation
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
is there any simple way (in Java 7) to:
open in reading mode a file containing, for every line, a path to another file
for every line/path, open the respective file and print the content
(Every file is a plain text file)
?
Sorry if the question is silly.
Thank you
try something like this:
public static void main(String[] args) throws IOException {
// open stream to path list file
InputStream indexSource = new FileInputStream("index.txt");
// create reader to read content
try(BufferedReader stream = new BufferedReader(new InputStreamReader(indexSource))) {
// loop
while (true) {
// read line
String line = stream.readLine();
if (line == null) {
// stream reached end, escape the loop
break;
}
// use `line`
printFile(line);
}
}
}
static void printFile(String path) throws IOException {
// open stream to text file
InputStream textSource = new FileInputStream(path);
// print file path
System.out.println("### " + path + " ###");
// create reader to read content
try(BufferedReader stream = new BufferedReader(new InputStreamReader(textSource))) {
// loop
while (true) {
// read line
String line = stream.readLine();
if (line == null) {
// stream reached end, escape the loop
break;
}
// print current line
System.out.println(line);
}
}
// nicer formatting
System.out.println();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have searched about this. All I got was xml parsing/ Sax parser. I need a program that will download xml data.
I need this for my android application development. thanks
For example i have a website localhost:8080/folder/sample.html.. How do i get a .xml file from that?
Sorry if I'm not answering the question - but is it the website content, you want to download? If positive, these are similar questions where the solution may lie:
How to get a web page's source code from Java
Get source of website in java
How do I retrieve a URL from a web site using Java?
How do you Programmatically Download a Webpage in Java
A good library to do URL Query String manipulation in Java
try this code:
public String getXmlText(String urlXml) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
String result = null;
try {
url = new URL(urlXml);
is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
result = result + line + "\n";
}
} catch (Exception e) {
return "";
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {}
}
return result;
}
Try this code
import java.net.*;
import java.io.*;
class Crawle {
public static void main(String ar[]) throws Exception {
URL url = new URL("http://www.foo.com/your_xml_file.xml");
InputStream io = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(io));
FileOutputStream fio = new FileOutputStream("file.xml");
PrintWriter pr = new PrintWriter(fio, true);
String data = "";
while ((data = br.readLine()) != null) {
pr.println(data);
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I print out every text file in a particular directory with BufferedReader? Because I have a method to create file in a particular directory, and at times I want to read out every text file I've created in that directory to know what I have created.
I hope this code to help you:
// Directory path here
String path = ".";
String files;
File folder = new File(path);
// Returns an array of the files in the directory denoted.
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
//Checks if the type of the file is a text file.
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
// Reads the file and show every line on the screen.
File file = listOfFiles[i];
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
file.getAbsolutePath()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
}
}
}
}
first list all files
public File[] listf(String directoryName) {
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
System.out.println(fList);
return fList;
}
and after that pass that list into the print(File[]) function
in print function you must print each file of list
1) First Google your self for solution after that try yourself to write something and test it ... still you have any issues come to Stackoverflow to Write a question
Try this one.. Not tested but it helps you i think
BufferedReader listReader = new BufferedReader(
new FileReader("c:/File_list.dat"));
String fileName;
while((fileName = listReader.readLine()) != null) {
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
String line;
while((line = fileReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
}
listReader.close();
Do you have a list of names of the files you want to read, or do you want ever last file in a folder that is readable to be read, you say "I want to read out every text file I've created in that directory to know what I have created." so it sounds like the first one to me,
And also what kind of code have you tried already, Here are some key phrases to google.
"java get all files in a directory"
"java how to read files"
There is already a ton of info out there on these subjects
but just for a quick search on the first one I find a similar question here.