How would I read a .txt file in Java and put every line in an array when every lines contains integers, strings, and doubles? And every line has different amounts of words/numbers.
I'm a complete noob in Java so sorry if this question is a bit stupid.
Thanks
Try the Scanner class which no one knows about but can do almost anything with text.
To get a reader for a file, use
File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
new FileInputStream (file), encoding));
... use reader ...
reader.close ();
You should really specify the encoding or else you will get strange results when you encounter umlauts, Unicode and the like.
Easiest option is to simply use the Apache Commons IO JAR and import the org.apache.commons.io.FileUtils class. There are many possibilities when using this class, but the most obvious would be as follows;
List<String> lines = FileUtils.readLines(new File("untitled.txt"));
It's that easy.
"Don't reinvent the wheel."
The best approach to read a file in Java is to open in, read line by line and process it and close the strea
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console - do what you want to do
System.out.println (strLine);
}
//Close the input stream
fstream.close();
To learn more about how to read file in Java, check out the article.
Your question is not very clear, so I'll only answer for the "read" part :
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("fileName"));
String line = br.readLine();
while (line != null)
{
lines.add(line);
line = br.readLine();
}
Common used:
String line = null;
File file = new File( "readme.txt" );
FileReader fr = null;
try
{
fr = new FileReader( file );
}
catch (FileNotFoundException e)
{
System.out.println( "File doesn't exists" );
e.printStackTrace();
}
BufferedReader br = new BufferedReader( fr );
try
{
while( (line = br.readLine()) != null )
{
System.out.println( line );
}
#user248921 first of all, you can store anything in string array , so you can make string array and store a line in array and use value in code whenever you want. you can use the below code to store heterogeneous(containing string, int, boolean,etc) lines in array.
public class user {
public static void main(String x[]) throws IOException{
BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
String[] user=new String[500];
String line="";
while ((line = b.readLine()) != null) {
user[i]=line;
System.out.println(user[1]);
i++;
}
}
}
This is a nice way to work with Streams and Collectors.
List<String> myList;
try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
myList = reader.lines() // This will return a Stream<String>
.collect(Collectors.toList());
}catch(Exception e){
e.printStackTrace();
}
When working with Streams you have also multiple methods to filter, manipulate or reduce your input.
For Java 11 you could use the next short approach:
Path path = Path.of("file.txt");
try (var reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
Or:
var path = Path.of("file.txt");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
Or:
Files.lines(Path.of("file.txt")).forEach(System.out::println);
Related
I have two files:
One is a CSV file that contains the following:
Class
weka.core.Memory
com.google.common.base.Objects
client.network.ForwardingObserver
Second is a txt file that contains the following:
1_tullibee com.ib.client.ExecutionFilter
107_weka weka.core.Memory
101_netweaver com.sap.managementconsole.soap.axis.sapcontrol.HeapInfo
107_weka weka.classifiers.Evaluation
guava com.google.common.base.Objects
57_hft-bomberman client.network.ForwardingObserver
18_jsecurity org.jsecurity.web.DefaultWebSecurityManager
I would like to retrieve the lines in the txt files that contain the classes in the CSV file. To do so:
try (BufferedReader br = new BufferedReader(new FileReader("/home/nasser/Desktop/Link to Software Testing/Experiments/running_scripts/exp_23/run3/CSV/MissingClasses_RW_No_Reduction.csv"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println("==>> " + line);
Scanner scanner = new Scanner(new File("/home/nasser/Desktop/Link to Software Testing/Experiments/running_scripts/exp_23/selection (copy).txt"));
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
if(currentLine.contains("**>> " + line)){
System.out.println(currentLine);
}else {
System.out.println("not found");
}
}
}
}
When I run it, I get not found with all the classes in the CSV which is not the case I expect. I expect the following lines to be printed:
107_weka weka.core.Memory
guava com.google.common.base.Objects
57_hft-bomberman client.network.ForwardingObserver
How to solve that?
If you don't want the not found and the ==>> * output, just delete the corresponding lines of code
try (BufferedReader br = new BufferedReader(new FileReader("csv.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Scanner scanner = new Scanner(new File("copy.txt"));
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
if (currentLine.contains(line)) {
System.out.println(currentLine);
}
}
scanner.close(); // added this, could use try-with but that is *advanced*
}
}
this will generate the following output, exactly as requested:
107_weka weka.core.Memory
guava com.google.common.base.Objects
57_hft-bomberman client.network.ForwardingObserver
obviously used files located in my folder...
Just my two cents: If you're using Java 8, and the CSV file is relatively small, you can simply do this:
List<String> csvLines = Files.lines(Paths.get(csvFilename))).collect(Collectors.toList());
Files.lines(Paths.get(txtFileName)))
.filter(txtLine -> csvLines.stream().anyMatch(txtLine::contains))
.forEach(System.out::println);
Scenario: I want to read an Arabic dataset with utf-8 encoding. Each word in each line is separated by a space.
Problem: When I read each line, the output is:
??????? ?? ???? ?? ???
Question: How can I read the file and print each line?
for more information, here is my Arabic dataset and part of my source code that reads data would be like the following:
private ContextCountsImpl extractContextCounts(Map<Integer, String> phraseMap) throws IOException {
Reader reader;
reader = new InputStreamReader(new FileInputStream(inputFile), "utf-8");
BufferedReader rdr = new BufferedReader(reader);
while (rdr.ready()) {
String line = rdr.readLine();
System.out.println(line);
List<String> phrases = splitLineInPhrases(line);
//any process on this file
}
}
I can read using UTF-8, Can you try like this.
public class ReadArabic {
public static void main(String[] args) {
try {
String line;
InputStream fileInputStream = new FileInputStream("arabic.txt");
Reader reader = new InputStreamReader(fileInputStream, "UTF-8"); // leave charset out for default
BufferedReader bufferedReader = new BufferedReader(reader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.err.println(e.getMessage()); // handle all exceptions
}
}
}
I am trying to read parts of a text file with the format
John Smith
72
160
The first line being the name (string), and the second and third lines being height and weight (both ints). However, I cannot find a way to store each of these into their own variables, instead I can only figure out how to store the whole thing into one variable and print it. This is the code that I have as of now
try
{
File file = new File("person.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println(stringBuffer);
}
In this part
stringBuffer.append(line);
stringBuffer.append("\n");
I was thinking of trying to add a part in the middle of both those lines that stored a variable, but it did not seem possible. I also thought of using a for loop and using that to my advantage somehow, but could not figure out a way to do it with that either.
Is there any possible way to do this that I do not know about? Thank you
Reading and parsing a text file in Java has been getting easier in every new version. You can try the following way:
List<String> lines = Files.lines(Paths.get("person.txt")).collect(Collectors.toList());
String name = lines.get(0);
Integer height = Integer.parseInt(lines.get(1));
Integer weight = Integer.parseInt(lines.get(2));
File file = new File("person.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String firstline = bufferedReader.readLine();
String secondline = bufferedReader.readLine();
String thirdline = bufferedReader.readLine();
fileReader.close();
I have a .txt file in this format:
file.txt (each line has text)
text1
text2
longtext3
...
..
I am downloding it:
URL url = new URL(FILE_URL);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = newBufferedInputStream(connection.getInputStream());
How can I parse this input so I get the text in each new line?
I tried something like that:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
LIST.add(line);
} }
but I don't want to save it,so I don't have the File instance
I can save in this format:
text1,text2,longtext3,....
If its more simple to extract it
You can use an InputStreamReader (http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html).
Put it between your InputStream and your BufferedReader. Now you don't need the File instance (and so there is no need to save it first).
Something like ...
InputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {
LIST.add(line);
// further break the line into a list of comma separated values
List<String> commaSeparatedValues = Arrays.asList(line.split(","));
}
...
You can use the Scanner class
String result = "";
Scanner in = new Scanner(new FileInputStream(file));
while(in.hasNextLine())
result += in.nextLine() + ",";
this will create a string like this:
text1,text2,longtext3,....
I'm not sure what you're asking but I think you want to save each line of a text file. This worked for me, it puts every line into one long string.
public static void main( String[] args )
{
String FILE_URL = "http://www.google.com/robots.txt";
String FILE_CONTENTS = "";
try
{
URL url = new URL(FILE_URL);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
while( line != null )
{
FILE_CONTENTS += line;
line = reader.readLine();
}
}
catch( MalformedURLException e )
{
System.out.println("Malformed URL" );
}
catch( IOException e )
{
System.out.println( "IOException" );
}
}
Try to scan as normal text and replace every '\n' in a comma...
I have a text file like this:
Item 1
Item 2
Item 3
I need to be able to read each "Item X" into a string and ideally store all the strings as a vector / ArrayList.
I tried:
InputStream is = new FileInputStream("file.txt");
is.read(); //looped for every line of text
but that seems to only handle integers.
Thanks
You have several answers here, the easiest would be to us a Scanner (in java.util).
It has several convenience methods like nextLine() and next() and nextInt(), so you could simply do the following:
Scanner scanner = new Scanner(new File("file.txt"));
List<String> text = new ArrayList<String>();
while (scanner.hasNextLine()) {
text.add(scanner.nextLine());
}
Alternatively you could use a BufferedReader (in java.io):
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
List<String> text = new ArrayList<String>();
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
However Scanners are generally easier to work with.
You should use FileUtils to do this. It has a method named readLines
public static List<String> readLines(File file, Charset encoding) throws IOException
Reads the contents of a file line by line to a List of Strings. The file is always closed.
See #BackSlash's comment above to see how you're using InputStream.read() wrong.
#BackSlash also mentioned you can use java.nio.file.Files#readAllLines but only if you're using Java 1.7 or later.
You could use Java 7's Files#readAllLines. A short one-liner and no 3rd party library imports necessary :)
List<String> lines =
Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
String [] tmp ;
while (line != null) {
sb.append(line);
tmp = line.Split(" ");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Scanner scan = new Scanner(new FileInputStream("file.txt"));
scan.nextLine();