I have a CSV file that is like:
Orbit,a,e,i
LEO,7168000,0,90
MEO,20200000,0,54
What I want is that using scanner, I will be able to choose one of the two orbits I have in the CSV file. Let's say for example, using scanner if I put 1 in the console, it chooses the row of the CSV file: LEO,7168000,0,90 and if I put 2 the line: MEO,20200000,0,54.
After that from the row chosen it saves each parameter in a variable skipping the name (LEO,MEO). For example if I choose LEO orbit, it saves the variables like:
double a = 7168000;
double e = 0;
double i = 90;
So in the end I can use those parameters in my program. Thank you for your answers.
Csv file is a plain text file and separates with , character for each cell and \n for each row.
The easy way, you only need using FileInputStream to read and split \n and , character for using.
File file = new File("file.csv");
FileInputStream fis = null;
String dataStr = "";
try {
fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
dataStr += (char) content;
}
} catch (IOException e) {
e.printStackTrace();
}
// convert to array rows string
String[] dataRows = dataStr.split("\n");
// loop rows to get cells string
for (int i = 0; i < dataRows.length; i++) {
String[] dataCells = rowData[i].split(",");
//do what ever you want with dataCells
}
Thanks for read.
Related
I really do not want to do a duplicate question, but none of the answers on SO were implementable in my problem.
The answer in this question:
How to read a file from a certain offset in Java?
uses RandomAccessFile, but the implementations I found need all the file lines to have the same length.
How can I get List lines = readLinesFromLine(file);?
I tried
private static List<String> readRandomAccessFile(String filepath, int lineStart, int lineEnd, int charsPerLine, String delimiter) {
File file = new File(filepath);
String data = "";
int bytesPerLine = charsPerLine+2;
try{
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
for (int i = lineStart; i <lineEnd ; i++) {
randomAccessFile.seek(bytesPerLine *i);
data = randomAccessFile.readLine();
dialogLineRead.add(data);
}
randomAccessFile.close();
}catch (Exception e){
e.printStackTrace();
}
String returnData = "";
for (int i = 0; i < dialogLineRead.size(); i++) {
returnData += dialogLineRead.get(i);
returnData+=delimiter;
}
return returnData;
But like I said charsPerLine has to be the same for each line.
I tried to count the chars of each line in a file, and store it in a list, but with a log file of 2gb, that takes to much ram.
Any ideas?
For a standard text file where you don't know the line lengths in advance, there's really no way around reading the whole thing line by line, like in this answer, for example.
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 3 years ago.
Improve this question
My teacher gave us homework to reverse a integer file.
lets say I have a file that contains 1,2,3,4,5.
My homework is to reverse it and write it into a file so it contains 5,4,3,2,1.
I already did that with List. and it worked.
But my teacher told me not to do it with List.
Can someone help me please ?
static void getNumFiles(File file){
InputStream inputStream = null;
OutputStream outputStream = null;
List<Integer> list = new ArrayList<>();
int actuallyRead = 0;
byte[] buffer = new byte[4];
int[] arr = new int[list.size()];
int counter = list.size();
int x = 0;
try {
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file);
while((actuallyRead = inputStream.read(buffer)) != -1){
x = ByteBuffer.wrap(buffer).getInt();
list.add(x);
}
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(list.size() - i) ;
}
exampleWriteIntegerArray(arr, file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This answer assumes the file in question is a simple text file. The file type was not clear in the original question.
Just a quick snippet of code that achieves your assignment without using a list.
It reads the input file and uses a StringBuilder to reverse the input. The reversed input can then be written to a desired output location.
public static void main(final String[] args) {
try {
String fileContent = new String(Files.readAllBytes(Paths.get("D:/12345.txt"))); // Read file
StringBuilder sb = new StringBuilder(fileContent);
String reversedContent = sb.reverse().toString();
PrintWriter writer = new PrintWriter(new File("D:/54321.txt")); // Create new file and output the reversed String.
writer.println(reversedContent);
writer.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
Input: 1,2,3,4,5
Output: 5,4,3,2,1
It's not entirely clear from your question what exactly your teacher expects from you. Also, it looks like the file is a binary file with integers rather than a text file with integer values.
If that is true, without writing the program for you:
Open your file as a RandomAccessFile.
Use its length() function to determine how many integers are contained in it (Note that the length is in bytes, while integers are 32 bit).
Move to the last int position in the file using the seek() method, read it using readInt(), output it.
Move one position before that, do the same, until you're at position 0 - at which point you've read the whole file.
If you use String's reverse function then you cannot handle the following situation 250,150,623changes to 326,051,052.
And also I cannot clearly understand the your files context. Does it contains the , character for delimiter character? If not, what is your file's delimiter?
At the beginning of my answer I said that you cannot handle that. However, if you know what is your files delimiter then you can use #ProfessionalCode's code with that extras,
public static void main(final String[] args) {
try {
String fileContent = new String(Files.readAllBytes(Paths.get("D:/12345.txt"))); // Read file
StringBuilder sb = new StringBuilder(fileContent);
String reversedContent = sb.reverse().toString();
char delimiter = " "; //let say it is whitespace
String temp = ""; //it will use between two delimiters to get reverse String
PrintWriter writer = new PrintWriter(new File("D:/54321.txt")); // Create new file and output the reversed String
for (int i = 0; i < reversedContent.length(); i++){
if(reverseContent.charAt(i) == delimiter){
writer.print(temp.reverse().toString());
writer.print(delimiter.reverse().toString()); //writing your delimiter between all numbers, if it is like ",-" it needed to be reversed to "-,"
temp = "";
}else{
temp += reverseContent.charAt(i);
}
}
writer.print(temp.reverse().toString()); //for last number
writer.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
I am a little stuck with a java exercise I am currently working on. I have a text file in this format:
Quio Kla,2221,3.6
Wow Pow,3332,9.3
Zou Tou,5556,9.7
Flo Po,8766,8.1
Andy Candy,3339,6.8
I now want to calculate the average of the whole third column, but I have to extract the data first I believe and store it in an array. I was able to read all the data with a buffered reader and print out the entire file in console, but that did not get me closer to get it into an array. Any suggestions on how I can read in a specific column of a text file with a buffered readder into an array would be highly appreciated.
Thank you very much in advance.
You can split your text file by using this portion of code:
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("textfile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split(",");
for (String part : splited) {
System.out.println(part);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
And then you'll have all your columns in the array part.
It`s definitely not the best solution, but should be sufficient for you
BufferedReader input = new BufferedReader(new FileReader("/file"));
int numOfColumn = 2;
String line = "";
ArrayList<Integer>lines = new ArrayList<>();
while ((line = input.readLine()) != null) {
lines.add(Integer.valueOf(line.split(",")[numOfColumn-1]));
}
long sum =0L;
for(int j:lines){
sum+=j;
}
int avg = (int)sum/lines.size();
I'm going to assume each data set is separated by newline characters in your text file.
ArrayList<Double> thirdColumn = new ArrayList<>();
BufferedReader in = null;
String line=null;
//initialize your reader here
while ((line = in.readLine())!=null){
String[] split = line.split(",");
if (split.length>2)
thirdColumn.add(Double.parseDouble(split[2]));
}
By the end of the while loop, you should have the thirdColumn ArrayList ready and populated with the required data.
The assumption is made that your data set has the following standard format.
String,Integer,Double
So naturally a split by a comma should give a String array of length 3, Where the String at index 2 contains your third column data.
I am getting exception thrown and i think it has to with the ArrayIndexOutOfBounds at the sub string and also do you think the below method would work for getting data passed to my array after parsing
I want this to be read from a txt file like this, on each line:
1
0
1
0
0
1
0
ONE INTEGER PER LINE!!
String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
data1 = scanner.nextLine();
}
for ( int i = 0; i < data1.length(); i++)
{
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}
This is previous working version but it reads from the console. where it would be : 1010101001
System.out.println("Enter the binary bits");
data1 = in.next();
for ( int i = 0; i < data1.length(); i++)
{
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}
You're reading all the lines and only keeping the last in your data1 variable. That's probably your problem.
You should, instead, handle each value right away while reading the file, and build an ArrayList instead of an array (because you won't know its size beforehand):
String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
ArrayList<Byte> covertDataList= new ArrayList<>();
while(scanner.hasNextLine()){
String line = scanner.nextLine(); // the line should be just a number
covertDataList.add(Byte.parseByte(line)); // no substring needed
}
If you want to fail nicely when the file format is wrong, you may surround parseByte with a try/catch block.
About the ArrayList
If you want to use your list as an array, you can just:
use covertDataList.get(i) instead of covertDataArray[i]
use covertDataList.set(i, value); instead of covertDataArray[i] = value;
If you really need an array (I don't see the point here), you can do this:
Byte[] covertDataArray = covertDataList.toArray(new Byte[list.size()]);
I have a text file with data. The file has information from all months. Imagine that the information for January occupy 50 lines. Than February starts and it occupies 40 more lines. Than I have March and so on... Is it possible to read only part of the file? Can I say "read from line X to line Y"? or is there a better way to accomplish this? I only want to print the data correspondent to one month not the all file. Here is my code
public static void readFile()
{
try
{
DataInputStream inputStream =
new DataInputStream(new FileInputStream("SpreadsheetDatabase2013.txt"));
while(inputStream.available() != 0)
{
System.out.println("AVAILABLE: " + inputStream.available());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readInt());
for (int i = 0; i < 40; i++)
{
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readDouble());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readBoolean());
System.out.println();
}
}// end while
inputStream.close();
}// end try
catch (Exception e)
{
System.out.println("An error has occurred.");
}//end catch
}//end method
Thank you for your time.
My approach to this would be to read the entire contents of the text file and store it in a ArrayList and read only the lines for the requested month.
Example:
Use this function to read the all the lines from the file.
/**
* Read from a file specified by the filePath.
*
* #param filePath
* The path of the file.
* #return List of lines in the file.
* #throws IOException
*/
public static ArrayList<String> readFromFile(String filePath)
throws IOException {
ArrayList<String> temp = new ArrayList<String>();
File file = new File(filePath);
if (file.exists()) {
BufferedReader brin;
brin = new BufferedReader(new FileReader(filePath));
String line = brin.readLine();
while (line != null) {
if (!line.equals(""))
temp.add(line);
line = brin.readLine();
}
brin.close();
}
return temp;
}
Then read only the ones you need from ArrayList temp.
Example:
if you want to read February month's data assuming its 50 lines of data and starts from 40th line.
for(int i=40;i<90;i++)
{
System.out.println(temp.get(i));
}
Note: This is only just one way of doing this. I am not certain if there is any other way!
I would use the scanner class.
Scanner scanner = new Scanner(filename);
Use scanner.nextLine() to get each of the lines of the file. If you only want from line x to line y you can use a for loop to scan each of the lines that you don't need before going through the scanner for the lines you do need. Be careful not to hit an exception without throwing it though.
Or you can go through the scanner and for each line, add the String contents of the line to an ArrayList. Good luck.
Based on how you said your data was organized, I would suggest doing something like this
ArrayList<String> temp = new ArrayList<String>();
int read = 0;
File file = new File(filePath);
if (file.exists()) {
BufferedReader brin;
brin = new BufferedReader(new FileReader(filePath));
String line = brin.readLine();
while (line != null) {
if (!line.equals("")){
if(line.equals("March"))
read = 1;
else if(line.equals("April"))
break;
else if(read == 1)
temp.add(line);
}
line = brin.readLine();
}
brin.close();
Just tried it myself, that'll take in all the data between March and April. You can adjust them as necessary or make them variables. Thanks to ngoa for the foundation code. Credit where credit is due
If you have Java 7, you can use Files.readAllLines(Path path, Charset cs), e.g.
Path path = // Path to "SpreadsheetDatabase2013.txt"
Charset charset = // "UTF-8" or whatever charset is used
List<String> allLines = Files.readAllLines(path, charset);
List<String> relevantLines = allLines.subList(x, y);
Where x (inclusive) and y (exclusive) indicates the line numbers that are of interest, see List.subList(int fromIndex, int toIndex).
One benefit of this solution, as stated in the JavaDoc of readAllLines():
This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.