Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I’m trying to create a Java String[] from the content of a file.
The code is:
private String[] arr;
private List<String> list = new ArrayList<String>();
public String[] readfile (String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
while((str = br.readLine()) != null){
list.add(str);
}
arr = list.toArray(new String[list.size()]);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null){
br.close();
}
} catch (IOException e2) {
e2.printStackTrace();
}
}
return arr;
}
The function apparently works. In fact, the variable arr contains the content of file.
However, after this line, arr = list.toArray(new String[list.size()]); the function doesn’t return arr. I get java.lang.StringIndexOutOfBoundsException: String index out of range: 0
What could be the problem?
Finally, the code I had provided was causing the exception. The problem is related to try catch block and variable scope.
Here, arr = list.toArray(new String[list.size()]); the variabe arr contains all lines of file. However, in this line return arr; the content is null;
For that, when I initialize the array and I put a simply return arr in the method, it works. In this case, I don’t have any try catch block.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 9 months ago.
Improve this question
I'm fairly new to Java.
Have the txt file of the following
25/05/2022 23:55:31,180.0,45.0,13.9,Underweight
30/05/2022 22:24:05,161.0,67.0,25.8,Overweight
30/05/2022 22:58:29,121.0,98.0,66.9,Obese
30/05/2022 22:58:38,168.0,67.0,23.7,Healthy
30/05/2022 23:25:58,140.0,54.0,27.6,Overweight
Is there any way of reading only the part of the following data in each line into an array?
13.9
25.8
66.9
23.7
27.6
Read through each line and split the line on , (comma). Access the value you want to print using the index;
Code:
import java.io.BufferedReader;
import java.io.FileReader;
public class SplitFileAndPrintPart {
public static void main(String[] args) {
String fileName = "TestFile.txt";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { //[#1]
String line;
while ((line = br.readLine()) != null) { // [#2]
String[] splitLine = line.split(","); // [#3]
System.out.println(splitLine[3]); // [#4]
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
#1: Reading the file using FileReader and BufferedReader; Here we are using "try with resources" so that the resources are closed automatically.
#2: Reading each line from the file and assigning it to the variable "line".
#3: Since the values are comma separated, splitting the lines using comma.
#4: Since the data you need in the 4 position (index 3), print the value at index 3.
Output:
13.9
25.8
66.9
23.7
27.6
First you will have to read the file using File class or some another class. You will have to read all lines and put that to List. Now these are lines and from these you can iterate and populate the final result (List) by using string.split(",") and the index you want to grab. This will be one possible way. But grabbing with index and hardcoding that might bring up issues later.
File file = new File("C:\\Users\\Desktop\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> lines = new ArrayList<>();
String string;
List<String> result = new ArrayList<>();
while ((string = br.readLine()) != null)
lines.add(string);
}
for(var line : lines){
String[] datas = line.split(",");
if(datas.size()>3){
results.add(datas[3]);
}
}
return lines;
References - https://techblogstation.com/java/read-text-file-in-java/#:~:text=Java%20read%20file%20line%20by%20line%20using%20Files.readAllLines,Internally%20it%20uses%20BufferedReader%20to%20read%20the%20file.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have two .txt file (file1.txt and file2.txt). In these file there are some lines of character. My intention is to merge the content of these two file into another file(file3.txt). My code is below:
public static void main(String[] args) {
try {
PrintWriter pw = new PrintWriter("file3.txt");
BufferedReader br1 = new BufferedReader(new FileReader("file1.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("file2.txt"));
String line = br1.readLine();
while(line!=null){
pw.println(line);
br1.readLine();
}
line = br2.readLine();
while (line!=null) {
pw.println(line);
br2.readLine();
}
pw.flush();
pw.close();
br1.close();
br2.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaIoProject.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JavaIoProject.class.getName()).log(Level.SEVERE, null, ex);
}
}
When compile there is no error. After running when i try to see expected output inside (file3.txt) it does not show anything and mouse pointer change to processing. Why this happens. Where is the missing part that i forgot to add or which part should i edit and why.. Need your help.. thanks.
You miss to reassign the value for line in the loop so you get an infinite loop.
Change both while loops:
while (line!=null) {
pw.println(line);
line =br2.readLine();
}
Lots of code you have repeated multiple times in your implementation. You can
simply create a method and invoke it as per filename.
PrintWriter pw = new PrintWriter("file3.txt");
readAndWrite(pw, "file1.txt");
readAndWrite(pw, "file2.txt");
pw.flush();
pw.close();
and this is definition of readAndWrite method. Also correct the loop.
private static void readAndWrite(PrintWriter pw, String filename) throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while (line!=null) {
pw.println(line);
line =br.readLine();
}
br.close();
}
You were missing the assignment. So You can try something like this.
String line ="";
while((line=br1.readLine())!=null){
pw.println(line);
}
line = "";
while ((line=br2.readLine())!=null) {
pw.println(line);
}
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
How can I remove lines which contains * using core Java, for example:-
hello how are you.
what are you * doing.
In the above example, I have to remove the entire line what are you * doing which contains * in the line.
it will work ..
String str="hello how are you. \nwhat are you * doing.";
str.replace("*","");
I think this will work fine for your problem:
String s="hello how are you. \nwhat are you * doing.";
String p[]=s.split("\n");
StringBuffer sb=new StringBuffer();
for(String n:p)
{
if(n.contains("*"))
{
//do nothing
}
else{
sb.append(n);
sb.append("\n");
}
}
System.out.println(sb);
I'm new to Java so if there's something wrong pls correct me, but I would suggest if you read out of a file:
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader bf = new BufferedReader(new InputStreamReader(fstream));
String s = bf.readLine();
if(s!=null)
{
if(s.contains("*"))
{
s="";
}
else
{
//work with the rest of your line stored in String
}
}
to put it in a loop (e.g. for or while)
you can simply use string methods contains.
String s="something *";
if(s.contains(*))
{
s="";
}
else
{
///do else
}
You could use 2 lists as per this code snippet:
List<String> originalList = Arrays.asList(
"hello how are you.",
"what are you * doing.");
List<String> filteredList = new ArrayList<>();
for (String item : originalList) {
if (!item.contains("*"))
filteredList.add(item);
}
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 just started to learn Java. As the title says... I would like to know how should I assign some values from a txt files to an array in Java to work with them (for example to sort them).
For example in C++:
#include<fstream>
using namespace std;
int v[10];
int main()
{
ifstream fin("num.txt");
int i;
for(i=0;i<10;i++)
fin>>v[i];
}
Right guys. Thank you for all the information. I see that is a little bit more complicated than C++, but I'll learn this. Furthermore, when I was intern at a small company I saw that the employees there made a code which scanns an XML files. I guess it's much more complicated, but that's fine. :)
If each line of the file is an integer then:
List<Integer> results = new ArrayList<Integer>();
try
{
File myFile = new File("./num.txt");
Scanner scanner = new Scanner(myFile);
while (scanner.hasNextInt())
{
results.add(scanner.nextInt());
}
}
catch (FileNotFoundException e)
{
// Error handling
}
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=read%20text%20file%20java
I believe this might help you find a solution.
Alright, getting that trolling out of the way.
PSEUDO CODE:
while not end of file
get next line
put next line in a Array List
Remember each line is a String you can parse strings with .split() to get all the words from the file or use some REGEX magic.
EDIT:
Ok I saw the other anwser and scanner.nextInt() makes me cringe. I had to show an actual code implementation. Using a REGEX to denot the pattern, is a farm more superior method. You can be reading garbage data for all you know! Even if REGEX is beyond you at the moment they are so freaking useful it's important to learn the correct method to do something.
List<Integer> list = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
if(line.matches("[\\s\\d]+"){
String[] temp = line.split(" ");
for(int i = 0; i < temp.length; i++){
list.add(Integer.parseInt(temp[i]));
}
}
}
The following program will read each character in the file to an ArrayList. In this example white spaces are loaded into the ArrayList, so if this is not intended you have to work some aditional logic :)
If the intention is to fill the array with words instead of characters, make a StringBuilder and inside the loop replace the logic with sb.append(new String(buffer));
Then, as progenhard suggested, use the split() method on the returning String from StringBuilder;
public class ReadFile {
public static void main(String[] args){
FileInputStream is = null;
try{
File file = new File("src/example/text");
is = new FileInputStream(file);
byte[] buffer = new byte[10];
List<Character> charArray = new ArrayList<Character>();
while(is.read(buffer) >=0){
for(int i=0;i < buffer.length;i++)
charArray.add((char)buffer[i]);
//Used remove the assigned values on buffer for the next iteration
Arrays.fill(buffer, (byte) 0);
}
for(char character : charArray){
System.out.println(character);
}
}catch(IOException e){
System.out.println("Something wrong with the file: " + e);
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
System.out.println("Something wrong when closing the stream: " + e);
}
}
}
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I need to read lines from an input path (file).
to do so the main calls a class that uses BufferedReader , it iterates over each line and adds it to an Array.
the problem is:
I want to catch all exceptions thrown from the method in the class in the main.
public static void main (String[] args){
if (args.length != 2){
System.err.print("ERROR");
return;
}
MyFileScript.sourceDir = args[SOURCE_DIR_INDEX];
MyFileScript.commandFile = args[COMMAND_INDEX];
try (FileReader file = new FileReader(MyFileScript.commandFile);
BufferedReader reader = new BufferedReader(file)){
fileParsing = new CommandFileParser(reader);
sectionList = fileParsing.parseFile();
}catch (FileNotFoundException error){
System.err.print(ERROR_MESSAGE);
return;
}catch(IOException error){
System.err.print(ERROR_MESSAGE);
return;
}catch(ErrorException error){
System.err.print(error.getMessage());
return;
}
}
public class CommandFileParser {
public CommandFileParser (BufferedReader reader){
this.reader = reader;
}
/**
* read all lines from a file.
*
* #return a string array containing all file lines
*/
public String[] readFileLines(){
ArrayList<String> fileLines = new ArrayList<String>();
String textLine;
while ((textLine = this.reader.readLine()) != null){
fileLines.add(textLine);
}
String[] allFileLines = new String[fileLines.size()];
fileLines.toArray(allFileLines);
return allFileLines;
}
in the while loop I get a compilation error for unhandling the IOException.
How can I catch all exceptions in main,
and so the class takes only one string argument?
your readFileLines method is lacking a throws clause.
public String[] readFileLines() throws IOException {