如何转换文本文件以便放置在我的 acharengine 数组中?

Posted

技术标签:

【中文标题】如何转换文本文件以便放置在我的 acharengine 数组中?【英文标题】:How to convert text file in order to be placed in my acharengine array? 【发布时间】:2016-05-22 09:58:27 【问题描述】:

所以我有两个名为ReadFromFile(由@Pankaj Nimgade 提供)和MainActivity 的类来导入和读取我的test.txt。我希望使用库 achartengine 在我的应用程序中读取文本文件上的整数。它们必须被格式化以放入 int[] force_lint[] force_r: 你能帮我按照我需要的方式格式化整数以及如何将它们放在 int[] force_lint[] force_r 中吗?

private void openChart() 
        int[] x = 0,1,2,3,4,5,6,7,8,9,10;
        int[] force_l = 0,25,24,25,15,16,17,25,24,21,24; //replace this  values with the ones from the text file
        int[] force_r = 0,48,36,26,43,45,30,33,33,28,42; //replace this  values with the ones from the text file

test.txt 有两行:

0 25 24 25 15 16 17 25 24 21 24
0 48 36 26 43 45 30 33 33 28 42

现在,如何从 ReadFromFile 传递整数字符串以在 MainActivity 中读取?

@Pankaj Nimgade 提供的 ReadFromFile 类:

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Arrays;
import java.util.List;

public class ReadFromFile 

    public static void main(String[] args) 

        int[] force_l = null;
        int[] force_r = null;
        try 

            File file = new File("test.txt");
            List<String> strings = FileUtils.readLines(file);
            int count = 0;
            for (String s : strings) 

                String[] integer_Strings = s.split(" ");
                if (count == 0) 

                    force_l = new int[integer_Strings.length];
                    for (int i = 0; i < integer_Strings.length; i++) 
                        force_l[i] = Integer.parseInt(integer_Strings[i]);
                    
                    count++;
                 else if (count == 1) 
                    force_r = new int[integer_Strings.length];
                    for (int i = 0; i < integer_Strings.length; i++) 
                        force_r[i] = Integer.parseInt(integer_Strings[i]);
                    
                

            

            System.out.println(Arrays.toString(force_l));
            System.out.println(Arrays.toString(force_r));


         catch (Exception e) 
        e.printStackTrace();
        
    


MainActivity 类:

import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import org.achartengine.ChartFactory;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.BasicStroke;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

public class MainActivity extends AppCompatActivity 

    private View mChart;
    private String[] mTime = new String[]
            "0",
            "1","2","3","4","5","6","7","8","9","10",
    ;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting reference to the button btn_chart
        Button btnChart = (Button) findViewById(R.id.btn_chart);

        // Defining click event listener for the button btn_chart
        View.OnClickListener clickListener = new View.OnClickListener() 

            @Override
            public void onClick(View v) 
                // Draw the Chart
                openChart();
            
        ;

        // Setting event click listener for the button btn_chart of the     SensorGraph layout
        btnChart.setOnClickListener(clickListener);

    

    private void openChart() 
        int[] x = 0,1,2,3,4,5,6,7,8,9,10;
        int[] force_l;
        int[] force_r;

        // Creating an XYSeries for Right Force
        XYSeries force_rSeries = new XYSeries("Force R (N)");
        // Creating an XYSeries for Left Force
        XYSeries force_lSeries = new XYSeries("Force L (N)");
        // Adding data to Force Series
        for (int i = 0; i < x.length; i++) 
            force_lSeries.add(i, force_l[i]);
            force_rSeries.add(i, force_r[i]);
        

        // Creating a dataset to hold each series
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        // Adding Left Force Series to dataset
        dataset.addSeries(force_lSeries);
        // Adding Right Force Series to the dataset
        dataset.addSeries(force_rSeries);

        // Creating XYSeriesRenderer to customize Force R Series
        XYSeriesRenderer force_rRenderer = new XYSeriesRenderer();
        force_rRenderer.setColor(Color.RED); //color of the graph set to green
        force_rRenderer.setFillPoints(true);
        force_rRenderer.setLineWidth(2f);
        force_rRenderer.setDisplayChartValues(false);
        //setting chart value distance
        // force_rRenderer.setDisplayChartValuesDistance(10);
        //setting line graph point style to circle
        // force_rRenderer.setPointStyle(PointStyle.CIRCLE);
        //setting stroke of the line chart to solid
        force_rRenderer.setStroke(BasicStroke.SOLID);

        // Creating XYSeriesRenderer to customize Force L Series
        XYSeriesRenderer force_lRenderer = new XYSeriesRenderer();
        force_lRenderer.setColor(Color.BLUE);
        force_lRenderer.setFillPoints(true);
        force_lRenderer.setLineWidth(2f);
        force_lRenderer.setDisplayChartValues(false);
        //setting line graph point style to circle
        // force_lRenderer.setPointStyle(PointStyle.SQUARE);
        //setting stroke of the line chart to solid
        force_lRenderer.setStroke(BasicStroke.SOLID);

        // Creating a XYMultipleSeriesRenderer to customize the whole chart
        XYMultipleSeriesRenderer multiRenderer = new     XYMultipleSeriesRenderer();
        multiRenderer.setXLabels(0);
        //multiRenderer.setChartTitle("High Speed");
        multiRenderer.setXTitle("time (s)");
        multiRenderer.setYTitle("Force (N)");

        /***
         * Customizing graphs
         */
        //setting text size of the title
        multiRenderer.setChartTitleTextSize(28);
        //setting text size of the axis title
        multiRenderer.setAxisTitleTextSize(24);
        //setting text size of the graph lable
         multiRenderer.setLabelsTextSize(24);
         //setting zoom buttons visiblity
         multiRenderer.setZoomButtonsVisible(false);
         //setting pan enablity which uses graph to move on both axis
        multiRenderer.setPanEnabled(false, false);
        //setting click false on graph
        multiRenderer.setClickEnabled(false);
        //setting zoom to false on both axis
        multiRenderer.setZoomEnabled(false, false);
        //setting lines to display on y axis
        multiRenderer.setShowGridY(true);
        //setting lines to display on x axis
        multiRenderer.setShowGridX(true);
        //setting legend to fit the screen size
        multiRenderer.setFitLegend(true);
        //setting displaying line on grid
        multiRenderer.setShowGrid(true);
        //setting zoom to false
        multiRenderer.setZoomEnabled(false);
        //setting external zoom functions to false
        multiRenderer.setExternalZoomEnabled(false);
        //setting displaying lines on graph to be formatted(like using graphics)
        multiRenderer.setAntialiasing(true);
        //setting to in scroll to false
        multiRenderer.setInScroll(false);
        //setting to set legend height of the graph
        multiRenderer.setLegendHeight(30);
        //setting x axis label align
        multiRenderer.setXLabelsAlign(Paint.Align.CENTER);
        //setting y axis label to align
        multiRenderer.setYLabelsAlign(Paint.Align.LEFT);
        //setting text style
        multiRenderer.setTextTypeface("sans_serif", Typeface.NORMAL);
        //setting no of values to display in y axis
        multiRenderer.setYLabels(10);
        // setting y axis max value, Since i'm using static values inside the graph so i'm setting y max value to 60.
        // if you use dynamic values then get the max y value and set here
        multiRenderer.setYAxisMin(0);
        multiRenderer.setYAxisMax(80);

        multiRenderer.setXLabels(4);
        //setting used to move the graph on xaxis to 0 to the right
        multiRenderer.setXAxisMin(0);
        //setting used to move the graph on xaxis to 0 to the right
        multiRenderer.setXAxisMax(61);
        //setting bar size or space between two bars
        //multiRenderer.setBarSpacing(0.5);
        //Setting background color of the graph to transparent
        multiRenderer.setBackgroundColor(Color.TRANSPARENT);
        //Setting margin color of the graph to transparent
        multiRenderer.setMarginsColor(Color.argb(0x00, 0x01, 0x01, 0x01));
        multiRenderer.setApplyBackgroundColor(true);
        multiRenderer.setScale(2f);
        //setting x axis point size
        multiRenderer.setPointSize(4f);
        //setting the margin size for the graph in the order top, left, bottom, right    
        multiRenderer.setMargins(new int[]30, 30, 30, 30);

        /*for(int i=0; i< x.length;i++)
            multiRenderer.addXTextLabel(i, mTime[i]);
        */

        // Adding Force L Renderer and Force R Renderer to multipleRenderer
        // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
        // should be same
        multiRenderer.addSeriesRenderer(force_lRenderer);
        multiRenderer.addSeriesRenderer(force_rRenderer);

        //this part is used to display graph on the xml
        LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart);
        //remove any views before u paint the chart
        chartContainer.removeAllViews();
        //drawing bar chart
        mChart = ChartFactory.getLineChartView(MainActivity.this, dataset, multiRenderer);
        //adding the view to the linearlayout
        chartContainer.addView(mChart);

    

【问题讨论】:

上面的代码遇到了什么问题? 问题是我不知道如何以我需要的方式格式化文本文件中的值,也不知道如何将它们导入 int[] force_l 和 int [] force_r 【参考方案1】:

你应该注意的事情是你得到单独的行,整数行用空格分隔,你可以从这里生成一个String 数组,像这样String[] integer_Strings = s.split(" "); 现在你有每个整数的字符串值,你可以像 Integer.parseInt("2") 一样将此字符串值转换为 int。此方法在int 2中返回2,代码也可在github中找到

    int[] force_l = null;
    int[] force_r = null;
    try 

        File file = new File("file_json_test_three.txt");
        Path path = file.toPath();
        List<String> strings = Files.readAllLines(path);
        //List<String> strings = FileUtils.readLines(file); can be used with common-io-2.4 library
        int count = 0;
        for (String s : strings) 
            //System.out.println(s);
            String[] integer_Strings = s.split(" ");
            //System.out.println(Arrays.deepToString(integer_Strings));
            if (count == 0) 
                force_l = new int[integer_Strings.length];
                for (int i = 0; i < integer_Strings.length; i++) 
                    force_l[i] = Integer.parseInt(integer_Strings[i]);
                
                count++;
             else if (count == 1) 
                force_r = new int[integer_Strings.length];
                for (int i = 0; i < integer_Strings.length; i++) 
                    force_r[i] = Integer.parseInt(integer_Strings[i]);
                
            

        

        System.out.println(Arrays.toString(force_l));
        System.out.println(Arrays.toString(force_r));


     catch (Exception e) 
        e.printStackTrace();
    

输出

[0, 25, 24, 25, 15, 16, 17, 25, 24, 21, 24]
[0, 48, 36, 26, 43, 45, 30, 33, 33, 28, 42]

【讨论】:

谢谢。它说“无法解析方法'toPath()',我在谷歌中找不到答案 @JoãoAmaro,它应该可以在 java 中工作,或者你可以试试 common-io-2.4 库,注释代码可以工作,代码在这里可用,github.com/pankajnimgade/JavaCoding_tutorials/blob/master/src/… 如果你愿意下载项目并运行它 @JoãoAmaro, java.io.File 你需要为 File 导入,你的 JDK 应该是 1.8 才能使用这个方法。或者您可以添加项目中可用的库(common-io-2.4) 升级到1.8后仍然无法在Android Studio中使用。那么如果我添加“common-io-2.4”,我应该评论什么,我应该取消评论什么? 注释这一行,Path path = file.toPath(); List strings = Files.readAllLines(path);... 并取消注释此行 List strings = FileUtils.readLines(file);,..... 您的代码可能会根据您的情况而改变读取文件(示例资产或原始文件)【参考方案2】:

使用 BufferedReader 逐行读取输入文件(请参阅此答案How to get file read line by line),并为每一行在“”(空格)上进行拆分

String line = "0 25 24 25 15 16 17 25 24 21 24"; /* this should be the line from file*/
String[] force_l  = line.split(" ");
force_l[0]; // this will contain "0"
force_l[1]; // this will contain " 25"

然后你可以将值转换为 int 像

Integer.parseInt(force_l[0])

同样将文件添加到资产中,你可以很容易地不使用像“C:/test.txt”这样的绝对路径

【讨论】:

以上是关于如何转换文本文件以便放置在我的 acharengine 数组中?的主要内容,如果未能解决你的问题,请参考以下文章

如何在组件中将“.json”文件显示为文本以便可以复制和粘贴?

孟加拉语文本未显示在Unicode CSV文件中

如何在居中的图像旁边放置文本?

将文本转换为 .docx 文档文件并打开共享对话框,Swift 2

如何解析 CSV 文件,以便可以被 Mahout 分类

如何将 .wav 音频文件转换为文本并使用 LUIS 识别意图