Java 7: a file containing paths to other files [closed] - java

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();
}

Related

How do i read multiple lines of input via the BufferedReader? [closed]

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 2 years ago.
Improve this question
I am developing a program that takes input from the console. So far it has been no problem reading input that consists of one line of input from the console. But the program does not work when it is supposed to read multiple lines. How can i improve the readInput method to read multiple lines of input and the return a single String containing all of the input from different lines.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
String input = inputstream.readLine();
return input;
}
So when you write String input = inputstream.readLine() This reads one line at a time,
As you are taking input from the user there would not be any null cases even if the user clicks enter, You need to check for the length of the input string, If it is 0 then break from the while loop.
But this isn't the case when you are reading from a file or other source you need to check whether the input is null or not.
Hope this could help you.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
StringBuilder finalString = new StringBuilder();
String input = inputstream.readLine();
while(true){
finalString.append(input);
input=inputstream.readLine();
if(input.length() == 0){
break;
}
}
br.close();
return finalString;
}
Input:
hi hello
how are you
Am fine
Output:
hi hellohow are youAm fine

How do i search through directories and return a file to a JTextArea [closed]

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.

Java, automatic reading file from a directory [closed]

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.

Retrieving a string by line number? Java [closed]

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 have 3 text files that all contain strings from objects.
I have a GUI with a list that is populated with the contents of one text file. Im currently looking to implement something that would take the line number from the first file and pull out the strings from the same line number in other files. Can anyone recommend anything?
You can use:
String[] lines = secondFileText.split("\n");
P.s.- If that doesn't work try replacing \n with \r\n.
You can split a string into lines:
String[] lines = s.split("\r?\n");
Then you can access the line at any index:
System.out.println(lines[0]); // The array starts at 0
Note: On Windows, the norm for ending lines is to use a carriage-return followed by a line-feed (CRLF). On Linux, the norm is just LF. The regular expression "\r?\n" caters for both cases - it matches zero or one ("?") carriage-returns ("\r") followed by a line-feed ("\n").
BufferedReader will deal well with huge files that won't fit in memory, it's pretty fast and deal with both \r and \n
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadByLine {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
File f = new File("xyz.txt");
int lineNumber = 666;
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
int count = -1;
try {
while((line = br.readLine())!=null){
count++;
if (count == lineNumber){
//get the line, do what you want
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
} catch (IOException e) {
br = null;
}
}
//do what you want with the line
}
}

How to create a text file that can be read again? [closed]

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 have taken a basic class on Java, but my knowledge is very little. I have created a text based rpg over the last month or two since I am getting more familiar with Java. I was wondering if there was any way I could have the program create a "save" file to be stored in a certain folder and prompt the user if they would like to open a saved character. I have not learned any of the object oriented parts of Java yet. What could I do to implement this?
I was wondering if there was any way I could have the program create a
"save" file to be stored in a certain folder and prompt the user if
they would like to open a saved character.
Writing and reading a text file is a solid beginner way to save states for games.
There are many ways to write to files listed here, but here's one example:
PrintWriter out = new PrintWriter("filename.txt");//create the writer object
out.println(text);//write
out.close() //when you're done writing, this will save
Now, here's a simple way to read a file found from here:
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));//objects to read with
try {
StringBuilder sb = new StringBuilder();//use to build a giant string from the file
String line = br.readLine();
//loop file line by line
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();//always close!
}
There are many tutorials online just a Google away. |=^]
NOTE: Always remember to close readers/writers/scanners/etc. Else wise you'll get resource errors which you can read more about here.
That’s the class I built to save text,
import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Savetext {
/**
* Saves text to a <i>.txt</i> file with the specified name,
*
* #param name the file name without the extension
*
* #param txt the text to be written in the file
*
* #param message the message to be displayed when done saving, if <tt>null</tt> no
* message will be displayed
*/
public static void Save(String name, String txt, String message) {
name += ".txt";
gtxt(name, txt, message);
}
private static void gtxt(String name, String txt, String mess) {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File file = null;
fc.showSaveDialog(null);
file = fc.getSelectedFile();
String path = file.getPath();
path += "\\";
path += name;
File f1 = new File(path);
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f1)));
wrtxt(out, txt, mess);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage().toString());
}
}
private static void wrtxt(PrintWriter out, String txt, String mess) {
out.println(txt);
out.flush();
out.close();
if (mess != null)
JOptionPane.showMessageDialog(null, mess);
}
}
you should call the static save() method,without making an instance of the class,

Categories

Resources