I'm working on a project for school, where I want to load questions from a file. However, Java is unable to load the file. I am sure the text file is named right and in the right direactory, but here they are:
game>src
game>out>production>game
private static void init(){
BufferedReader br = null;
ArrayList<String> strings= new ArrayList<String>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(new File("questions.txt")));
while ((sCurrentLine = br.readLine()) != null) {
strings.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
int i = 0;
while(i < strings.size()){
String text = strings.get(i++);
int numAnswers = Integer.parseInt(strings.get(i++));
ArrayList<String> answers = new ArrayList<String>();
for (int i2 = 0; i2 < numAnswers; i2++){
answers.add(strings.get(i++));
}
questions.add(new Question(text, answers));
}
}
Try scr/questions.txt as path.
br = new BufferedReader(new FileReader(new File("src/questions.txt")));
Related
I have a file and it contains name, surname and age information. For example: Mike, Tyson, 54. There is 1 person in every 1 row. I just want to read the names. How can I do that? I did the reading of all lines, but I could not only read the name.
public static void main(String[] args) {
File f = new File("C:/Users/muham/Desktop/students.txt");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String s = reader.readLine();
String[] students = new String[6];
int i=0;
while(s != null){
students[i] = s;
s=reader.readLine();
i++;
}
Arrays.sort(students);
String[] arr = null;
for(i = 0; i<students.length;i++){
System.out.println(students[i]);
}
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
}
Use split to get the name try this code
public static void main(String[] args) {
File f = new File("C:/Users/muham/Desktop/students.txt");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String s = reader.readLine();
String[] students = new String[6];
int i=0;
while(s != null){
students[i] = s.split(",")[0];
s=reader.readLine();
i++;
}
//Arrays.sort(students);
String[] arr = null;
for(i = 0; i<students.length;i++){
System.out.println(students[i]);
}
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
}
I am trying to read lines from a file. For this, I am using the following code:
try {
String line;
try (InputStream fis = new FileInputStream("AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
FactGeneration.getFacts();
while ((line = br.readLine()) != null) {
br.readLine();
function1(line);
However, this does not move to the next line in the file.
Thank you!
Edit:
For clarity, I am making a twitter bot. The entire function looks like this:
FactGeneration.getFacts() appends a new line to the file located at /AbsoluteFilePath
private static void tweetLines() {
String tweet;
int count = 0;
while (count < 10) {
try {
try (InputStream fis = new FileInputStream(
"/AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
FactGeneration.getFacts();
while ((tweet = br.readLine()) != null) {
sendTweet(tweet);
try {
int sleepTime = 18000;
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
count += 1;
}
}
Edit:
The following is the working code:
while (count < numTweets) {
try {
try (InputStream fis = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr)) {
//Calls static method GetFacts from the FactGeneration class.
FactGeneration.getFacts();
tweet = br.readLine();
while (tweet != null) {
//sendTweet accesses the TwitterAPI and posts the tweet.
sendTweet(tweet);
System.out.println("tweeting:" + tweet);
try {
//Pauses the thread for the given amount of time.
int sleepTime = 18000; //in milliseconds.
System.out.printf("Sleeping for %d seconds", sleepTime / 1000);
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
e.printStackTrace();
}
//moves to the next line in the file.
tweet = br.readLine();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
count += 1;
if (count == numTweets) {
System.out.println("Tweet limit reached");
}
}
The readLine actually reads a line, it does it inside the condition of the while loop, so don't read a second time inside the loop
String line;
try (InputStream fis = new FileInputStream("AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
// do whatever with line
}
}
The while condition has 2 steps, this allows, that at the end, it reads null and stop looping
read a line from the file and assign the result to line
check that line is not null
I've got the file, which can vary in size, in terms of lines. The only thing I know is that it's made of same modules of, lets say, 7 lines. So it means that .txt can be 7, 14, 21, 70, 77 etc. lines. I need to get only header of each module - line 0, 7 and so on.
I've written this code for the job:
textFile = new File(Environment.getExternalStorageDirectory() + "/WorkingDir/" + "modules.txt" );
List<String> headers = new ArrayList<>();
if (textFile.exists()) {
try {
FileInputStream fs= new FileInputStream(textFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fs));
int lines = 0;
int headLine = 0;
while (reader.readLine() != null) { lines++;}
Log.i("Debug", Integer.toString(lines));
while(headLine < lines){
for (int i = 0; i < dateLine - 1; i++)
{
reader.readLine();
Log.i("Debug", reader.readLine());
}
headers.add(reader.readLine());
headLine += 7;
}
Log.i("Debug", headers.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is that it always returns [null]. I do not know where's the problem, since I used similar questions from overflow as references.
ArrayList<String> headerLines = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
// process the line.
if(lineCount % 7 == 0) {
heaaderLines.add(line);
}
lineCount ++;
}
} catch (IOException ioEx) {
ioEx.printStackTrace();
} finally {
br.close();
}
Part of my homework.
I have written a method to split all words to ArrayList. Words are taken from all files in given project directory.
Unfortunately sometimes lines are skipped... and I wish to find the bug. Please help.
To specify: files are of 7 "words" separated with tabs in each line.
public class TravelData {
static List<String> tour = new ArrayList<String>(); //lista zlokalizowana według nagłówka wiersza
public TravelData(File dataDir) {
String currentDirPath = new File(dataDir.toString()).getAbsolutePath();
File currentDir = new File(currentDirPath);
File[] listOfFiles = currentDir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
try {
Scanner s = new Scanner(new File(listOfFiles[i].toString()));
while (s.hasNextLine()){
ArrayList<String> line = new ArrayList<String>();
for(String value: s.nextLine().split("\t"))
{
line.add(value);
}
lineConverter(line, dbDate); //do something with grabbed data
}
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
//[...]
}
I've personally not used Scanners much, so I can't immediately spot the issue. But here is some old code using buffered file input stream that I've added your specific bits to:
public TravelData(File dataDir) {
File[] listOfFiles = dataDir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
InputStream inputStream = null;
BufferedReader buffReader = null;
try {
inputStream = new FileInputStream(listOfFiles[i]);
buffReader = new BufferedReader(new InputStreamReader(inputStream));
String fileLine = buffReader.readLine();
while(fileLine != null) {
ArrayList<String> line = new ArrayList<String>();
for(String value: fileLine.split("\t")) {
line.add(value);
}
lineConverter(line, dbDate);
fileLine = buffReader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(buffReader != null) try { buffReader.close(); } catch (IOException e) { }
if(inputStream != null) try { inputStream.close(); } catch (IOException e) { }
}
}
}
}
Could someone shed me light on why strange characters does not appear in Android listView?
I have a text file with this
And I got this
Here is my code
ArrayList<String> list = new ArrayList<String>();
InputStream inStream = getResources().openRawResource(R.raw.emoticons);
InputStreamReader inputReader = null;
if (inStream != null)
{
try {
inputReader = new InputStreamReader(inStream, "UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
int c, i=0;
//int i=0;
char [] cb = new char[1];
byte [] buf = new byte[100];
String line = "";
int ble = -1;
try {
ble = inputReader.read(cb, 0, 1);
}catch (IOException e){
e.printStackTrace();
}
while (ble > -1)
{
if(cb[0] == '\r' || cb[0] == '\n')
{
try{
line = new String(buf, 0, i, "UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
i=0;
list.add(line);
}
else
{
buf[i++] = (byte) cb[0];
}
try {
ble = inputReader.read(cb, 0, 1);
}catch (IOException e){
e.printStackTrace();
}
}
}
String[] emoticons = list.toArray(new String[list.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, emoticons);
listview.setAdapter(adapter);
It looks like you are trying read a file line-by-line. One way to do that is using the BufferedReader class:
ArrayList<String> list = new ArrayList<String>();
InputStream inStream = getResources().openRawResource(R.raw.emoticons);
BufferedReader inputReader = null;
if (inStream != null)
{
try {
inputReader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
String line;
while ((line = inputReader.readLine()) != null) {
list.add(line);
}
// handle exceptions..
} finally {
if (inputReader != null) inputReader.close();
}
}
String[] emoticons = list.toArray(new String[list.size()]);