So i have an array int[] numbers = {1,2};
But i want the 1,2 to be removed and replaced with numbers from an txt file.
I can see the numbers from the files in the console with this method:
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static void testFileArrayProvider() throws IOException {
algo1 fap = new algo1();
String[] lines = fap
.readLines("D:/Users/XXX/workspace/abc/src/abc1/Filename123");
for (String line : lines) {
System.out.println(line);
}
}
NOw i need to save them in the array. BUt how? xd
Thx guys
This should work:
// In your case this is already populated
String[] lines = new String[] {"123", "4567"};
// Easier to work with lists first
List<Integer> results = new ArrayList<>();
for (String line : lines) {
results.add(Integer.parseInt(line));
}
// If you really want it to be int[] for some reason
int[] finalResults = new int[results.size()];
for (int i = 0; i < results.size(); i++) {
finalResults[i] = results.get(i);
}
// This is only to prove it worked
System.out.println(Arrays.toString(finalResults));
In Java-8, you can shorten it to
int[] finalResults = Arrays.stream(lines).mapToInt(Integer::parseInt).toArray();
Related
I want to save every line in my files into an Array List.
When i have only one file it works fine, but if i readin multiple files the first line of every file are all saved in the same Array...
Code:
public static void main(String[] args)
{
File folder = new File("\\Documents\\Files");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
}
public static void dosomething(File file)
{
try {
List<String[]> lines = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String[] tmp;
String line;
while ((line = reader.readLine()) != null) {
tmp = line.split("\n");
if (tmp.length > 0) {
lines.add(tmp);
}
}
reader.close();
System.out.println(lines.get(0));
}
....
}
Result:
[Ljava.lang.String;#15db9742
[Ljava.lang.String;#6d06d69c
[Ljava.lang.String;#7852e922
In my folder "files" i have 3 file.txt and every file contains lines of text.
So i wanted do save every line of every file into a new Array. But why i have no 3 Lines saved instead of 1 one?
Can someone helpme?
Thanks
Now i tried it this way:
public static String [] stringArr;
public static void main(String[] args)
{
File folder = new File("\\Documents\\Files");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
List<String> lines = new ArrayList<>();
for(String s : stringArr)
{
lines.add(s);
}
for(String t : lines)
{
System.out.println(t);
}
}
public static void dosomething(File file)
{
try {
List<String> list= new ArrayList<>();
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while((str = in.readLine()) != null){
list.add(str);
}
stringArr = list.toArray(new String[0]);
}
reader.close();
}
Result: If do a for-loop of stringArr in the dosomthing methode, every contant of each file perfectly saved in my stringArr.... but now if i do the for loop in the Main-methode i just get the content of one file back...
First of all you don't need a list of arrays to store the lines but can be simply stored in a String.
so
List<String> lines=new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
lines.add(tmp);
}
will suffice the need of storing the lines from file into your arraylist.
For printing the lines from the list you can just iterate over your list and print them.
for(String string : lines ){
System.out.println(string);
}
EDIT after OP edited the question
1.Why to again use String[] stringArr instead use it as a list and add lines to it. I see your whole intention is to store the lines of all three files in a list(or array) which is used to print them all at once
public List<String> globalList;
public static void main(String[] args)
{
globalList=newArrayList<String>();
File folder = new File("\\Documents\\Files");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for(String t : globalList) {
System.out.println(t);
}
}
public static void dosomething(File file)
{
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while((str = in.readLine()) != null){
globalList.add(str);
}
}
reader.close();
}
import java.util.*;
import java.io.*;
public class readFiles2 {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new FileReader("someFile.txt"));
try{
StringBuilder text = new StringBuilder();
String readStringLine = reader.readLine();
String[] lines= {};
for(int i = 0; readStringLine != null; i++){
readStringLine = reader.readLine();
//Trying to save seperate lines of text in an array.
lines[i] = readStringLine.toString();
}
}
finally{
reader.close();
}
}
So what I'm trying to do is save separate lines of strings from a .txt file to a String[] array. I'm kind of at a loss right now and don't really know what else I can do.
Since you don't know how many strings there are for your array, you might want to put the strings in a list and convert to an array at the end:
String readStringLine;
List<String> lines = new ArrayList<String>();
while((readStringLine = reader.readLine()) != null) {
lines.add(readStringLine);
}
String[] linesArray = lines.toArray(new String[lines.size()]);
Edit: Simpified to use a while loop to gather the line from the reader.
ArrayList<String> line = new ArrayList<>();
FileReader file = new FileReader(file.txt);
BufferedReader reader = new BufferedReader(file);
while (reader.ready()) {
line.add(reader.readLine());
reader.close();
file.close();
}
To acess, use line.get(i); where i>=0 and i<=array.size
Using autocloseable interface and Java 8 streams:
String [] stringsArray = null;
try(BufferedReader br = new BufferedReader(new FileReader("someFile.txt"))) {
List<String> strings = new ArrayList<>();
br.lines().forEach(c -> strings.add(c));
stringsArray = strings.toArray(new String[strings.size()]);
}
You need Java 8 to run this code
Making a hangman style of game
I have the random word now. How do I replace the letters of the word with an asterix * so that when the program starts the word is shown as *.
I assume that when someone inputs a letter for the hangman game you get the index of that character in the word and then replace the corresponding *.
public class JavaApplication10 {
public static String[] wordArray = new String[1];
public static String file_dir = "Animals.txt";
public static String selectedWord = "";
public static char[] wordCharacter = new char[1];
Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
wordArray = get_word(file_dir);
selectedWord = select_word(wordArray);
System.out.println(selectedWord);
}
public static String[] get_word(String file_dir) throws IOException {
FileReader fileReader = new FileReader(file_dir);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static String select_word(String[] wordArray) {
Random rand = new Random();
int lines = Math.abs(rand.nextInt(wordArray.length)- 1);
return wordArray[lines];
}
}
If you know how many lines are there you could use Random method in java with a specific range to pick out a line at random.
Then you could read the file line-by-line till you reach that random line and print it.
// Open the file
FileInputStream fstream = new FileInputStream("testfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int counter=0;
//While-loop -> Read File Line By Line till the end of file
//And will also terminate when the required line is printed
while ((strLine = br.readLine()) != null && counter!=randomValue){
counter++;
//You need to set randomValue using the Random method as suggested
if(counter==randomValue)
// Print the content on the console
System.out.println (strLine+"\n");
}
//Close the input stream
br.close();
Assuming Java 8:
// Loading ...
Random R = new Random(System.currentTimeMillis());
List<String> animals = Files.readAllLines(Paths.get(path));
// ...
// When using
String randomAnimal = animals.get(R.nextInt(animals.size()));
Answer of your first question :
First you have to get the total number of lines
Then you have to generate a random number between 1 and that total number.
Finally, get the required word
try {
InputStream is = new BufferedInputStream(new FileInputStream("D:\\test.txt"));
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
int noOfLines = count+1;
System.out.println(noOfLines);
Random random = new Random();
int randomInt = random.nextInt(noOfLines);
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader bufferedReader =
new BufferedReader(fr);
String line = null;
int counter =1;
while((line = bufferedReader.readLine()) != null) {
if(counter == randomInt)
{
System.out.println(line); // This the word you want
}
counter++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
//is.close();
}
I am creating a function to print a mase, which is stored in a 2 Dimensional ArrayList<ArrayList<String>>. However, the function instead prints out a large portion of blank space. I am attempting to first iterate through each ArrayList<String> and then iterate through each String element inside the nested ArrayList<String>s. I am creating the ArrayList<ArrayList<String>> from reading a file.
Here is the file:
XXXXXXXXSOOOOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXOOOOOXXXXXX
XXXXXXXOXXXXXXXXXXX
XXXXXXXEXXXXXXXXXXX
Here is where I create it:
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null)
{
ArrayList<String> lineList = new ArrayList<String>();
for (int i = 0; i < line.length(); i++)
{
lineList.add(line.substring(i, i));
}
lines.add(lineList);
}
Here is my function:
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
System.out.println(elem);
}
}
}
There are just some minor mistakes in your code. Make the following changes.
// This is adding a blank space
lineList.add(line.substring(i, i));
To
// This will add a single character
lineList.add(line.substring(i, i+1));
and modify printMase(ArrayList<ArrayList<String>> lines)
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
// Using print so each character is on the same line
System.out.print(elem);
}
// Now use println to end the line
System.out.println();
}
}
Full code looks like:
public static void main(String[] args) throws Exception {
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null) {
ArrayList<String> lineList = new ArrayList<>();
for (int i = 0; i < line.length(); i++) {
// Adds a single character
lineList.add(line.substring(i, i+1));
}
lines.add(lineList);
}
printMase(lines);
}
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
// Using print so each character is on the same line
System.out.print(elem);
}
// Now use println to end the line
System.out.println();
}
}
Results:
XXXXXXXXSOOOOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXOOOOOXXXXXXX
XXXXXXXOXXXXXXXXXXX
XXXXXXXEXXXXXXXXXXX
Woops, I realized that I was adding blank space during initialization. I updated my code such that it was adding the actual characters:
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null)
{
ArrayList<String> lineList = new ArrayList<String>();
for (int i = 0; i < line.length(); i++)
{
lineList.add(Character.toString(line.charAt(i)));
}
lines.add(lineList);
}
I am learning Java and in order to learn more about Java IO I am making a program to read a file path and return an array that contains everything from the file. I didn't want to specify that the data had to be integers so I've been working in strings. I'm running into an issue when I try to run a method returning an array. Is there a better way I should be writing this code?
import java.io.*;
public class OrganizeIO
{
public static void main(String[] args) throws Exception
{
String sampleData[] = readFile("C://Users/Tweak/workspace/FileIO/resources/data.txt");
int i = 0;
while(sampleData[i] != null)
{
System.out.print(sampleData[i]);
i++;
}
}
public static String[] readFile(String file) throws IOException
{
BufferedReader br = null;
String currentLine;
String[] data;
br = new BufferedReader(new FileReader(file));
int i = 0;
while((currentLine = br.readLine()) != null)
{
System.out.println(currentLine);
currentLine = data[i];
i++;
}
return data[];
}
}
You're not storing anything in data, not to mention you haven't even initialized it (which results in a compilation error). You should be using a List anyway, since you don't know how many lines you are going to read beforehand:
List<String> data = new ArrayList<String>();
while ((currentLine = br.readLine()) != null) {
data.add(currentLine);
}
return data.toArray(new String[data.size()]); // or just return the list?
Also, don't forget to close your BufferedReader:
br.close();
Well for one it looks like you while loop should be
while((currentLine = br.readLine()) != null)
{
System.out.println(currentLine);
data[i] = currentLine;
i++;
}
because you are returning nothing
I think you can work with the class Scanner to read the file and store it in a List.
// Open the file
Scanner scanner = new Scanner(new File("C:\\Users\\Tweak\\workspace\\FileIO\\resources\\data.txt"));
// Read the file line by line
List<String> result = new ArrayList<String>();
while (scanner.hasNext())
{
result.add(scanner.nextLine());
}
scanner.close();
// If you want an array
String sampleData[] = result.toArray(new String[result.size()]);
Since you don't know how many lines you get, storing the read lines directly in an array is inappropriate, better take a List implementation for that:
public static List<String> readFile (File file, String encoding) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
List<String> result = new LinkedList<String>();
String line;
while ((line = reader.readLine()) != null) {
result.add(line);
}
return result;
}
Usage:
public static void main (String[] args) throws IOException {
File file = new File("C://Users/Tweak/workspace/FileIO/resources/data.txt");
List<String> lines = readFile(file, "UTF-8");
for (String line : lines) {
System.out.println(line);
}
}
You can of course convert the List into a String array later, if that's what you want:
String[] linesArray = lines.toArray(new String[0]);